Dependency Injection in PHP

Dependency injection is the process by which one object provides the dependencies of another object. Dependency injection is a software design approach that avoids hard-coded dependencies and allows you to change dependencies at runtime and compile time.

Lets take a look along with the examples. Lets say we have a Food class that will supply dependency to Dinner Class.

<?php
class Food
{
    protected $food;
    
    public function __construct($food)
    {
    	$this->food = $food;
    }
    
    public function get()
    {
    	return $this->food;
    }
}

After that, lets create a dinner class without dependency injection first.

<?php
class Dinner
{   
    public function eat()
    {
    	$food = new Food("Chicken soup");
        return $food->get();
    }
}

$dinner = new Dinner();
echo $dinner->eat(); //output - Chicken soup

In the above style of Dinner class, we have hardcoded food class that is bad in coupling and not well dependency injected. Lets fix our dinner class using dependency injection.

<?php 

class Dinner
{  
	protected $dinner;
    
    //receiving the dependency object food.
	public function __construct(Food $food)
    {
    	$this->dinner = $food;
    }
    
    public function eat()
    {
        return $this->dinner->get();
    }
}

$food = new Food("Chicken soup");
//supplying the food object.
$dinner = new Dinner($food);
echo $dinner->eat(); //output - Chicken soup

Now, we have added a constructor to be injected the necessary food dependency object. The code is now loosely coupled and not hardcoded in dinner class anymore.

By Yuuma.



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム