The last lesson ended with the dependency inversion principle. It states that we shouldn’t depend on concrete service classes but on the interfaces they implement. Let’s dive deeper and see how this looks in practice.

Implementing dependency injections

Let’s imagine we’re building an application for a theater, and we want to provide two endpoints—one that lists play IDs and another that shows a specific play name. Such endpoints are impractical, and we’re not going to implement this application. But, let’s look at the code structure for this case.

We’ll have a single controller and two services–PlayListService and PlayNameService. Each service depends on two interfaces—PlayRepository to retrievie plays and LoggerInterface to write logs.

Here’s how we can implement this. We’ll keep all the important code in main.php and the not-so-interesting classes in separate files so it’s easier to focus.

Manual service initialization

Get hands-on with 1200+ tech skills courses.