Skip to content

Commit

Permalink
ioc sugar
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonmay committed Dec 15, 2010
1 parent c22b669 commit 92d76a8
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
43 changes: 41 additions & 2 deletions lib/IoC.pm6
@@ -1,9 +1,48 @@
module IoC;

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

my %cc;
my %containers;
my $container-name;

sub container($pair) is export {
# XXX
%containers{$pair.key} = IoC::Container.new(
:name($pair.key),
);

$container-name = $pair.key;

unless $pair.value.^isa('Block') {
die "Second param must be invocable";
}

$pair.value.();

return %containers{$container-name};
}

sub contains(Block $sub) is export { return $sub }

sub service($pair) is export {
my %params = ('name' => $pair.key, $pair.value.pairs);


my $service-class;
if %params<block> {
$service-class = 'IoC::BlockInjection';
}
elsif %params<class> {
$service-class = 'IoC::ConstructorInjection';
}
else {
warn "Service {$pair.key} needs more parameters";
return;
}

my $service = eval("{$service-class}.new(|%params)");
#my $service = $service-class.new(|%params);

%containers{$container-name}.add-service($pair.key, $service);
}
30 changes: 30 additions & 0 deletions t/02-sugar.t
@@ -0,0 +1,30 @@
BEGIN { @*INC.push('lib') };

use IoC;
use Test;
plan(5);

class Bar {};
class Foo { has Bar $.bar; };
my $c = container 'mycont' => contains {
service 'foo' => {
lifecycle => 'Singleton',
'class' => 'Foo',
dependencies => {'bar' => 'bar'},
};

service 'bar' => {
lifecycle => 'Singleton',
'block' => sub {
return Bar.new();
},
};
};

ok($c.fetch('foo').get);
ok($c.fetch('bar').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 92d76a8

Please sign in to comment.