PHP Dependency Injection

Keyword: PHP-DI, PSR-11, Autowriing

Dependency injection allow you inject an object into another object1.

Dependency Injection Container is the way to manage injecting and reading objects and third party libraries in your application.

PHP-FIG PSR-112 is a standard guide you to implement container.

interface ContainerInterface {
    public function get($id);
    public function has($id);


class Wheel


class Car
    private $wheel;

    public function __construct(Wheel $wheel)
      $this->wheel = $wheel;

$wheel = new Wheel;

$car = new Car($wheel);

At above example, every new Car object need Wheel object. That is dependency. new Car object is dependent on Wheel object.

As we can see, PSR-11 define two method has and get. get method will resolve dependency by using Reflection3. It provides autowiring4.

PHP has native Reflection5.

Want study more about dependency injection, check out PHP-DI6.

There is also another example demo a very simple container7.