Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonmay committed Dec 15, 2010
0 parents commit c22b669
Show file tree
Hide file tree
Showing 8 changed files with 122 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
Makefile
blib
9 changes: 9 additions & 0 deletions lib/IoC.pm6
@@ -0,0 +1,9 @@
module IoC;

use IoC::Container;

my %cc;

sub container($pair) is export {
# XXX
}
15 changes: 15 additions & 0 deletions lib/IoC/BlockInjection.pm6
@@ -0,0 +1,15 @@
use IoC::Service;
class IoC::BlockInjection does IoC::Service {
has Sub $.block;
has $.class;

method get {
if ($!lifecycle eq 'Singleton') {
return (
$!instance ||= $!block.();
);
}

return $!block.();
}
};
28 changes: 28 additions & 0 deletions lib/IoC/ConstructorInjection.pm6
@@ -0,0 +1,28 @@
use IoC::Service;
class IoC::ConstructorInjection does IoC::Service {
has Str $.class;
has %.dependencies = ();
has %.parameters;
has $.container is rw;

method get {
if ($!lifecycle eq 'Singleton') {
return (
$!instance ||= self.build-instance();
);
}

return self.build-instance();
}

method build-instance {
my %params;

for %!dependencies.pairs -> $pair {
%params{$pair.key} = $!container.fetch($pair.value).get();
};

return $!class.new(|%params);
}
};

15 changes: 15 additions & 0 deletions lib/IoC/Container.pm6
@@ -0,0 +1,15 @@
class IoC::Container {
has %!services = ();

method add-service($name, $service) {
if $service.^can('container') {
$service.container = self;
}
$service.name = $name;
%!services{$name} = $service;
}

method fetch($service-name) {
return %!services{$service-name};
}
};
7 changes: 7 additions & 0 deletions lib/IoC/Literal.pm6
@@ -0,0 +1,7 @@
use IoC::Service;

class IoC::Literal does IoC::Service {
has $.value;

method get { return self.value }
};
7 changes: 7 additions & 0 deletions lib/IoC/Service.pm6
@@ -0,0 +1,7 @@
role IoC::Service {
has Str $.name is rw;
has Str $!lifecycle;

# for singletons
has Any $!instance;
};
39 changes: 39 additions & 0 deletions t/01-basic.t
@@ -0,0 +1,39 @@
BEGIN { @*INC.push('lib') };

use IoC::Container;
use IoC::ConstructorInjection;
use IoC::BlockInjection;
use Test;

plan 4;

my $c = IoC::Container.new();

class Bar {};
class Foo { has Bar $.bar; };

$c.add-service(
'foo', IoC::ConstructorInjection.new(
:class('Foo'),
:lifecycle('Singleton'),
:dependencies({
'bar' => 'bar',
}),
)
);

$c.add-service(
'bar', IoC::BlockInjection.new(
:class('Bar'),
:lifecycle('Singleton'),
:block(sub {
return Bar.new;
}),
)
);

ok($c.fetch('foo').get);
ok($c.fetch('bar').get);

ok($c.fetch('foo').get.bar);
is($c.fetch('foo').get.bar, $c.fetch('bar').get);

0 comments on commit c22b669

Please sign in to comment.