kaihempel/simpledi

Simple dependency injection container

1.1.0 2016-07-15 22:11 UTC

This package is not auto-updated.

Last update: 2024-05-19 05:40:32 UTC


README

Simple PHP dependency injection bundle

Build Status Scrutinizer Code Quality Code Coverage

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.