Dependency Injection in PHP
- 2020年11月30日
- 技術情報
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.
yuuma at 2020年11月30日 11:00:23