Simple DI Container for PHP < 5.3
Acne is simple DI Container for PHP < 5.2, (*1)
Heavily inspired by fabpot/Pimple, (*2)
You can use Acne_Container
like an associative array., (*3)
Just set value with key., (*4)
<?php $container = new Acne_Container; $container['session.cookie_name'] = 'PHPSESSID';
Service provider is factory which constructs an object., (*5)
Closure
can be a service provider and it is the most prefferable way for PHP >= 5.3, (*6)
<?php $container['session'] = function ($c) { return new Session($c['session.cookie_name']); }; $container['session.cookie_name'] = 'PHPSESSID';
But if you're using PHP < 5.3, you can't use Closure
., (*7)
This is why I create Acne
., (*8)
Also the other callable
values can be set as service provider.
But notice that string
can't be a service provider., (*9)
<?php class ServiceProviderCollection { public function provideSession($c) { return new Session($c['session.cookie_name']); } } $providerCollection = new ServiceProviderCollection; $container['session'] = array($providerCollection, 'provideSession'); $container['session.cookie_name'] = 'PHPSESSID';
After you defined service provider, you can get object which the provider constructed., (*10)
<?php $session = $container['session']; $name = $session->get('name');
If you want to share objects like Singleton pattern, you can use shared service provider., (*11)
Shared service provider constructs object only once., (*12)
<?php $container->share('session', function ($c) { return new Session($c['session.cookie_name']); });
Pimple-like way is also available., (*13)
<?php $container['session'] = $container->share(function ($c) { return new Session($c['session.cookie_name']); });
Yuya Takeyama, (*14)