What Is Dependency Injection in PHP and How You Can Use It to Write Better Code

Tomasz Dobrowolski
3 min readMar 5, 2022
Person coding with headphones on
Photo by Jefferson Santos on Unsplash

If you are familiar with PHP, you have probably come across the term Dependency Injection.

While it sounds complex, it’s not as scary as it sounds on the surface. And if used correctly, it can transform your code to be cleaner and easier to work with.

Here’s all you need to know about dependency injection:

What is dependency injection?

To break it down: Dependency Injection is the process of passing objects into another object.

The object we are creating has a dependency on another object to do its job.

So how do we use dependency injection? By passing in the object (dependency) as a parameter in a constructor or a regular function.

The point of dependency injection is to handle the creation of an object outside of the class. The object is passed in as a parameter, rather than doing the instantiation inside the class.

How do you use dependency injection in PHP?

Let's say we have an Order class.

The idea of this class is to create an order. But for an order to be created, we need to check if a payment has been made.

--

--

Tomasz Dobrowolski
Tomasz Dobrowolski

Written by Tomasz Dobrowolski

I break down Software Engineering and Tech concepts | Backend Engineer 🐘