In the previous blog post we have discussed how to replace the default Pimple Container with Aura.DI in Slim framework 3. Aura.DI gives us more flexibility in terms of managing dependencies. We saw one most useful feature in Aura.DI, Inheritance of contructor parameters, that will help us to avoid repeating common parameters for Controllers and Models. In this article we will see another advantage of the same feature.
One thing that people often complains about the default Pimple DI implementation in Slim 3 is that, it require us to manually create object of each classes. Like, this example from slim3-skeleton by akrabat.
$container['App\Action\HomeAction'] = function ($c) {
return new App\Action\HomeAction($c->get('view'), $c->get('logger'));
};
It will become a mess as the application grows. When there is large number of classes, it will become difficult to create object of each Controller classes and setting their dependencies. This can be easily solved if we are using Aura.DI for dependency injection.
Slim 3 internally uses a CallableResolver for creating controller objects. If the requested controller is in the container, resolver simply calls the requested method on that object. Otherwise CallableResolver creates an object using new
. We will just update this part to use the di container for creating objects.
CallableResolver is declared as a final class in Slim. So we cannot extend it, instead we should create our own.
We will do this in slim-skeleton project I have already created.
First, copy the CallableResolver from Slim to our project folder. Then replace all the occurrences new $class
with $this->container->newInstance($class)
. This will delegate the object creation to the container.
Next, we need to set this class as the callableResolver for Slim in di container.
// app/config/dependencies.php
$di->set('callableResolver', new App\CallableResolver($di));
Now we are ready to go. We can create as many controllers as we need without registering them in di, as long as they have the same constructor signature. Checkout slim-skeleton for the complete example. Let me know your feedback :)