Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

initial commit

  • Loading branch information...
commit c22b6690e73f50217934331f99d79fe2cc90d626 0 parents
@jasonmay authored
2  .gitignore
@@ -0,0 +1,2 @@
+Makefile
+blib
9 lib/IoC.pm6
@@ -0,0 +1,9 @@
+module IoC;
+
+use IoC::Container;
+
+my %cc;
+
+sub container($pair) is export {
+ # XXX
+}
15 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 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 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 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 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 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);
Please sign in to comment.
Something went wrong with that request. Please try again.