I’m actually quite annoyed, for once. I remember reading a completely lucid description of Dependency Injection some time ago, but recently I’ve done a brief search of the web for documents on the subject and they’re unanimously impenetrable, at least for someone with my attention span. So here’s my explaination of DI Catalogues in as few words as I can.
Firstly we need a catalogue:
1 2 3 4 5 6 7 8 |
package Catalogue; sub new { bless {}, $_[0] } sub get { my ($self, $thing) = @_; $self->{$thing}->($self); } |
Next we need to populate it:
1 2 3 4 5 6 7 |
my $catalogue = new Catalogue(); $catalogue->{Foo} = sub { my ($c) = @_; new Foo($c->get('Bar'), $c->get('Baz')); }; $catalogue->{Bar} = sub { new Bar() }; $catalogue->{Baz} = sub { new Baz() }; |
Finally we get to use it:
1 |
my $foo = $catalogue->get('Foo'); |
That is all there is to it! Of course this omits all error checking, but you can add that yourself once you understand the principles.