Reputation: 1995
I don't understand how is this "DI container" used. The examples shown on the official site tell me nothing: http://pimple.sensiolabs.org
Basically I have a simple site, that consists of a set of classes: the DB class, the Cache class, User class and a few more that handle content types.
All these classes are like "services" mentioned in Pimple, and each service should be able to call another service. Right now I'm instantiating the services in a main class which I use it like a singleton to share services across other classes.
From what I read, Pimple does exactly this sort of thing, but how do I use it? :s
Upvotes: 17
Views: 12377
Reputation: 316939
There is a tutorial at http://phpmaster.com/dependency-injection-with-pimple/ explaining how to use Pimple as a DIC.
Another (but not necessarily recommended) approach is to inject the container into all the components that need it (e.g. you use it like a ServiceLocator) and then you just do what the documentation says you should do to get an object from Pimple:
class SomeClassThatNeedsSession
{
private $session;
public function __construct(Pimple $container)
{
$this->session = $container['session'];
}
}
In other words, you just fetch what you need and Pimple will handle the lifetime of that object, e.g. whether it needs to be created or is reused. OffsetGet is part of the ArrayAccess
interface which allows you to access an Object like an Array, so when you do $container['foo']
Pimple will check whether it has a closure defined for foo of whether its just some param and assemble the service accordingly.
Pimple was the result of a blog post about Lambdas and Closures which you might want to read to better understand how it works.
Upvotes: 19
Reputation: 308733
I don't know Pimple, but the DI engine I do know takes instantiation off your hands. Your objects don't create instances of their dependencies. Instead, the DI engine creates them and doles them out on request.
So if your PHP code is creating new instances, I think you should change it so your code gets the DI engine and asks for dependencies from it.
Upvotes: 4