kaihempel / simpledi
Simple dependency injection container
Requires
- php: >=5.4.0
- kaihempel/simplehash: 1.0.*
Requires (Dev)
- mockery/mockery: 0.9.*
- phpunit/phpunit: 4.6.*
This package is not auto-updated.
Last update: 2025-01-12 08:27:10 UTC
README
Simple PHP dependency injection bundle
This dependency injection container based on the idea to add the object construction code as closure. So every dependency can build with less convention restrictions.
Installing simpledi via Composer.
"require": { "kaihempel/simpledi": "1.1.*" }
Create the dependency injection container instance:
$di = new \SimpleDI\SimpleDI();
Adding closures for instance creation:
$di->add('author', function($name) { return new Author($name); });
After adding the closure with the name "autor", the closure can be executed by calling the magic get method:
$author = $di->getAuthor($name);
To create instance with further dependencys, the dependency injection container can be commited to the closure by using the "use" keyword:
$di->add('book', function($name) use ($di) { return new Book($di->getAuthor($name)); });
Like the description above, the "Book" instance will be initialized with a new author instance.
The container has a storage to save created objects. This feature have to be enabled by calling the "getStored()" method before calling the closure code:
$storedBook = $di->getStored() ->getBook($name);
If no Book instance is stored, the closure execution saves the new instance in the storage.