Dependency injector
What is a Dependency injector?
Instead of creating objects directly in your code, you can pass them in as dependencies. It let´s you effortlessly integrate your services into other services and controllers. But what does this mean?
Suppose you have four service classes named:
Http\Services\YourFirstService
Http\Services\YourSecondService
Http\Services\YourThirdService
Http\Services\YourFourthService
YourSecondService serve as dependencies for YourFirstService, while YourFourthService is dependent on YourThirdService.
1. Without a Dependency Injector
Without a Dependency Injector, you might handle it like this (not recommended):
Even though this is a simple example where class objects have a maximum of 2 levels, it still looks somewhat messy. But imagine if the classes had 4 levels of dependencies – without a dependency injector, you would lose control.
2. With the Dependency Injector
With the Dependency Injector, you can streamline the process:
Not as complicated anymore, thanks to the Dependency Injector, which automatically resolves all dependencies. That is what makes the Dependency injector a valuable tool in your arsenal.
How do I access the Dependency injector?
Controllers will have the Dependency injector loaded by default. This means that if you load a Service class in your Controller, all dependencies of that Service will be automatically resolved and so on until all Services/dependencies has been initiated.
The Dependency Injector is specifically designed to work with the __construct method. However, you can still access it manually within a regular method like this:
Don't worry if you don't fully comprehend what the Dependency Injector is and how it works. In the next step, I will start showing you some working examples. Let's move on and talk about the Controller.
Last updated