Last active
July 27, 2024 07:05
-
-
Save BrianDouglasIE/0b10304730ae87ecd4459e63213cff5e to your computer and use it in GitHub Desktop.
A DI Container without auto wiring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Container { | |
has %!bindings = (); | |
method set(Str $abstract, Callable $factory) { | |
if not %!bindings{$abstract}:exists { | |
%!bindings{$abstract} = $factory; | |
} | |
} | |
method get(Str $abstract) { | |
if %!bindings{$abstract}:exists { | |
return %!bindings{$abstract}(self); | |
} | |
} | |
} | |
my $container = Container.new; | |
class Logger { | |
method log(Str $text) { | |
say $text; | |
} | |
} | |
class SessionStorage { | |
has Logger $!logger; | |
method new(Logger $logger) { | |
self.bless(logger => $logger); | |
} | |
method create() { | |
$!logger.log('Session Created'); | |
} | |
} | |
class User { | |
has SessionStorage $.session; | |
method new(SessionStorage $session!) { | |
self.bless(session => $session); | |
} | |
method authenticate() { | |
$!session.create(); | |
} | |
} | |
$container.set('Logger', -> Container $c { Logger.new }); | |
$container.set('SessionStorage', -> Container $c { SessionStorage.new($c.get('Logger')) }); | |
$container.set('User', -> Container $c { User.new($c.get('SessionStorage')) }); | |
my $user = $container.get('User'); | |
$user.authenticate(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment