I like a lot this definition: “Dependency Injection” is a 25-dollar term for a 5-cent concept. Dependency injection means giving an object its instance variables.
In that approach, the CalculatorModel instance is created inside the controller in every action:
We say that CalculatorController depends on CalculatorModel because we need a CalculatorModel instance inside the controller.
There is repeated code in every calculator operation where the model is needed. This can be solved creating the model instance in the CalculatorController constructor. But what if we need this service in many other controllers. Same instantiation code will be in every constructor.
The solution for it is creating that dependency outside the controller and then inject it to the controller.
In a professional framework this task is done by an special component called Dependency Injection Container. In our simple framework, as we done with the routing task, it will be done in the index.php file (the Front Controller).
public/index.php
The model can be injected to the controller via constructor or via setter method. In our implementation we use the constructor.
The setter method can be used when at construction time the instance is not ready for receiving the dependency.
Then we have to modify our controller and to create a new property for the service:
application/controllers/CalculatorController.php
So now the model or service instance is created only one time in our application and it is injected to whatever other object that needs it. That instance can be shared or a new one for every different object.
Depending on interfaces
You can also make your classes more independent if they depend on interfaces. In that case multiple classes can implement that interface and can be used as a dependency.