How to build your own dependency injection

Posted date: Jul 09, 2022

Dependency Injection PHP

You recently started working on a framework that doesn’t support dependency injection or you are building your own project from scratch and you need to find out a way on how to build your own dependency injection? Here is how

Install PHP-DI

For the purpose of this task we’ll use a dependency injection container called php-di

Run on your project root
composer require php-di/php-di

Usage example

Assuming that we have 4 classes.

  • Warehouse
  • Box
  • Tomatoes
  • Apples

Then we need to achieve this.

<?php

use DI\Container;
use Box;
class Warehouse {
    
    public function __construct(
        Box $box
    ) {
        $this->box = $box;
    }

    public function getProducts()
    {
        return $this->box->getProducts();
    }
}
<?php

use Apple;
use Tomato;

class Box {
    
    public function __construct(
        Tomato $tomato,
        Apple $apple
    )
    {
        $this->tomato;
        $this->apple;
    }

    public function getProducts()
    {
        return [$this->tomato, $this->apple];
    }
}

Without dependency injection the way to do it is this.

<?php

$apple = new Apple();
$tomato = new Tomato();

$box = new Box(
    $apple,
    $tomato
);

$warehouse = new Warehouse($box);

$products = $warehouse->getProducts(); 

Assuming that your project has loads of classes this is not the best way to do it.

Equivalent implementation using PHP-DI

<?php

use DI\Container;
use Warehouse;

class Bootstrap {
    
    private $warehouse;

    public function init()
    {
        $container = new Container();
        $this->warehouse = $container->get(Warehouse::class);
    }

    public function getWarehouseProducts()
    {
        return $this->warehouse->getProducts();
    }
}

You can initialize the Warehouse class using PHP-DI and the rest will be done automatically.