Dependency injection container
Recently, for a project I’ve been working on, I had to choose a container bundle that will do the dirty job.
The solution is not using any ‚framework’ , so to keep things simple, one of the obvious choice was Pimple: http://pimple.sensiolabs.org/
Although developed in sensiolabs (the same guys behind Symfony) I had a feeling it’s not really what I need…
I started researching and trying it on my own. One think that really stroke me was that it’s only usable when the whole container has been passed through to the constructor. Then, inside a controller I was able to ‚get’ a certain service. In reality it’s not a dependency injection pattern, it’s just a service locator, as each controller will have to have a dependency of the locator and a number of _hidden_ dependencies of some services. That’s not what I had in mind.
So I decided to choose a full-blown solution that is: Symfony dependency injection container.
It’s not really that more complicated or difficult but offers a _real_ isolation of dependencies.
Installation is simple:
composer require symfony/dependency-injection
composer require symfony/symfony/yaml
Composer will sugest a couple more packages, but I don’t need them for now.
Then, all that’s needed to initialize the container is:
include __DIR__ . "/vendor/autoload.php";
$container = new ContainerBuilder();
$loader = new YamlFileLoader($container, new FileLocator(__DIR__));
And.. that’s it…