Dependency injection in Slim framework 2
Slim framework comes with a Dependency Injection container called Set. The basics The DIC is accessed via the container property of $app. To set, you use the set() method:
1 |
$app->container->set('foobar', function() { return new Foo\Bar(); } ); |
If you need a given resource to be shared, then use the singleton method:
1 |
$app->container->singleton('foobar', function() { return new Foo\Bar(); } ); |
And then to retrieve from the container, there are multiple ways to do it:
1 2 3 |
$fooBar = $app->container->get('foobar'); $fooBar = $app->container['foobar']; $fooBar = $app->foobar; |
The shortcut version ($app->foobar) only works if the key is a valid PHP variable name.… continue reading.