In this talk, I introduce the concept of Dependency Injection as well as Pimple as an example for a Dependency Injection Container. I also talk about one thing that you absolutely do *not* want to do when using Dependency Injection Containers.
services your class needs to run • Use setter injection for optional dependencies – services your class may use if available • Program against interfaces, not concrete implementations!
function($dic) { return new Foo($dic['db'], $dic['cache']); }; // Later in your application: $foo = $dic['foo']; var_dump($foo instanceof Foo); // true
as $dic['foo'] • Closure needs $dic['db'] and $dic['cache'], means more calls to Pimple::offsetGet() • Cascade closure / Pimple::offsetGet() calls until dependencies are resolved
a class: $dic['example'] = $dic->share(function($dic) { return new Example(); }); // To return the closure instead of executing it: $dic['closure'] = $dic->protect(function() { // Do cool stuff here });
dependencies by passing the DIC (or any other Service Locator) to them • You get to pull exactly ONE object out of the DIC yourself: The controller that needs to be executed.