Pimple, the small dependency injection container for PHP 5.3

Fabien Potencier

June 16, 2009

Some people emailed me about a blog post I wrote some time ago about a dependency injection container done in PHP 5.3. I have published on Github the small version of it (Twittee), but not the "working" version.

Today, I took the time to publish it on Github. Pimple is a small dependency injection container, with all the features you need for a usage in real projects.

Feel free to use it, fork it, and enhance it for your next PHP 5.3 project.

And don't forget to give PHP 5.3 a try as the PHP core team has just published the third release candidate, and they hope to release the final version by the end of June.

Discussion

gravatar David Herrmann  — June 16, 2009 13:14   #1
What shall I say... I love it! That's what programming should be nowadays: simple and more effective than some hundreds lines of code in other projects.
gravatar Ariel Arjona  — June 16, 2009 13:58   #2
very appropriate (albeit gross) name ;)
gravatar Jonathan Nieto  — June 17, 2009 01:51   #3
Really impressive!.
gravatar Piwa├»  — June 21, 2009 19:55   #4
I love the concept !!

After reading this, I started wondering if I could do quite the same using Java... I ended up actually implementing it, and even using it in an Android application.

For those interested, you can now have a look at Yasdic over there : http://code.google.com/p/yasdic/

I couldn't use lambda functions, so I used anonymous classes instead ;-)

I implemented a bit more things then what Pimple do, such as preventing cyclic dependencies.

Here is a copy&paste of how to do quite the same thing with Pimple and with Yasdic.

$container = new Pimple();
$container->cookie_name = 'SESSION_ID';
$container->storage_class = 'SessionStorage';
$container->storage = function ($c)
{
return new $c->storage_class($c->cookie_name);
};
$container->user = $c->asShared(function ($c)
{
return new User($c->storage);
});
$user = $container->user;
*********************************************************
YasdicContainer container = new YasdicContainer();
container.define("cookie_name", "SESSION_ID");
container.define("storage_class", SessionStorage.class);
container.define("storage", false, new BeanDef<IStorage>() {
protected IStorage newBean(YasdicContainer c) {
try { IStorage storage = (Class<IStorage>) c.getBean("storage_class").newInstance();
storage.setCookieName((String) c.getBean("cookie_name"));
return storage;
} catch (Exception e) {throw new RuntimeException(e);}
}
});
container.define("user", new BeanDef<User>() {
protected User newBean(YasdicContainer c) {
return new User((IStorage) c.getBean("storage"));
}
});
User user = (User) container.getBean("user");

Thanks again Fabien for this post ! I now have a much better dependency injection in my Android apps.