The aim of PHP-DI is to make Dependency Injection as simple as possible with PHP.
Unlike Flow3, Zend\DI, Symfony Service Container or Pimple (though they are of a great inspiration), PHP-DI:
- can be used by a monkey
- is non-intrusive and compatible with any framework
- is not limited to Services (anything can be injected)
- uses annotations for code-readability and ease of use
- can find and instantiate dependencies automatically without configuration
- Simple, yet full-featured
- Uses annotations for simplicity, readability and auto-completion in your IDE
- Automatic dependency resolution: you don't have to declare all your beans in configuration files
- Optional lazy-loading of dependencies
- Cacheable for optimal performances
- Class aliases (interface-implementation mapping)
- Easy installation with Composer and easy integration with Zend Framework (see Getting started)
- Non-intrusive: you can add PHP-DI into an existing project and use it without impacting existing code
Read the introduction to dependency injection with an example.
<?php
use DI\Annotations\Inject;
class Foo {
/**
* @Inject
* @var Bar
*/
private $bar;
public function __construct() {
// The dependency is injected
return $this->bar->sayHello();
}
}
In this example, a instance of the Bar
class is created and injected in the Foo
class. No configuration needed.
That's as easy as possible!
Of course, in the spirit of Dependency Injection, Bar
will rather be an interface, and you will configure
which implementation will be injected through configuration.
Do you want more? PHP-DI comes on top of a classic, full-featured Dependency Injection container:
$container = \DI\Container::getInstance();
$container['dbAdapter'] = $myDbAdapter;
$myDbAdapter = $container['dbAdapter'];
A more complete version of the previous example:
$container = \DI\Container::getInstance();
$container['db.params'] = [
'dbname' => 'foo',
'user' => 'root',
'password' => '',
];
$container['dbAdapter'] = function(Container $c) {
return new MyDbAdapter($c['db.params']);
};
and later:
class Foo {
/**
* @Inject("dbAdapter")
*/
private $dbAdapter;
public function foo() {
return $this->dbAdapter->query("");
}
}
- PHP-DI sources are on Github.
- Read the doc: Contributing
PHP-DI is license under the MIT License.