Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Pimple

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

like image 997
Anna K. Avatar asked May 21 '12 12:05

Anna K.


People also ask

Is it better to pop a pimple?

It's tempting, but popping or squeezing a pimple won't necessarily get rid of the problem. Squeezing can push bacteria and pus deeper into the skin, which might cause more swelling and redness. Squeezing also can lead to scabs and might leave you with permanent pits or scars.

What does a pimple indicate?

Pimples are a common skin condition caused by clogged or inflamed oil glands or an increased presence of pimple-causing bacteria on your skin. They're a symptom of acne, and there are many different types, including blackheads, whiteheads, cysts and others.


2 Answers

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.

like image 128
Gordon Avatar answered Oct 02 '22 00:10

Gordon


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.

like image 22
duffymo Avatar answered Oct 02 '22 02:10

duffymo