PHP Dependency Injection for dummies

Jorge Castro
Cook php
Published in
2 min readOct 4, 2018

Why you should use and why you shouldn’t!.

Let’s say the next exercise. We have a service class that convert a money into another unit. In this case, it transform dollar to euro (by multiplying by 1.15)

It has two functions, one (example) where we give a money and it returns the conversion, and another function (conversor) to do the conversion.

The code works however it’s not flexible to convert it back from euro to dollar. And it’s here we could use dependency injection.

It works in this fashion.

  • The function is inside another class (a service class). it could be one or more than one. In this case, the function is inside ServiceDollarToEuro and ServiceEuroToDollar
  • We use interface to generalize the code. On PHP, Interface is not required but it’s used to clarity of the code.
  • In the main class ClassConvertMoneyWithInjection, we “injected” the service class by using the function setService. We could also use a constructor to inject it. In fact, it’s based in the concept of we are changing a variable and the variable carries the function.

So the function is inside a variable and a variable is, ahem, variable (changeable), so then the function is also mutable.

Finally, we could execute the code as follow:

What is cool about it, we could convert into different types of money by only “injecting” a new service class , for example, we could create a new Service Class called ServiceDollarToYen and it will work

An injectable code is flexible, and it allows to run operations that aren’t even be developed.

However, the drawback is the cost of debugging. Let’s say that the operation failed.

Where did it fail?

If you check the code, $service is who do the trick. However, it’s defined by an interface, i.e. it’s not clear which class, it could be an instance of a ServiceDollarToEuro or ServiceEuroToDollar or maybe anotherIt is not defined in the code, and it’s hard to debug. It’s not as easy as to backtrace to find where is the bug.

class ClassConvertMoneyWithInjection
{
/** @var IConversor */
public $service;
public function setService(IConversor $srv) {
$this->service=$srv;
}
public function example($money) {
echo "$money is converted in ".$this->service->conversor($money)."<br>";
}
}

Dependency Injection (DI) is not for every case. It worths if the project is designed to be expanded. If not, then it increases the development time and gives nothing in exchange.

tl/dr: It mustn’t be used for every single case and situation, it must be used if the project is expand-able.

--

--