Dependency Injection is a process by which the components a class uses are supplied to it by a container instead of the class itself locating them. This allows a ton of flexibility for testing, special cases, and polymorhpism, and it follows the "tell, don't ask" software design principle.
The Xyster team has implemented a Dependency Injection container based very heavily on Java's PicoContainer. Here's an example of how you might use the container. (This example is adapted from one listed on the PicoContainer site).
interface Peelable {
function peel();
}
class Apple implements Peelable {
public function peel()
{
}
}
class Peeler {
private $_peelable;
public function __construct(Peelable $peelable)
{
$this->_peelable = $peelable;
}
}
class Juicer {
private $_peelable;
private $_peeler;
public function __construct(Peelable $peelable, Peeler $peeler)
{
$this->_peelable = $peelable;
$this->_peeler = $peeler;
}
} Add components:
$container = new Xyster_Container;
$container->addComponent('Apple');
$container->addComponent('Juicer');
$container->addComponent('Peeler');Get component with dependencies injected:
$juicer = $container->getComponent('Juicer');If you're curious about the implementation and would like to test it out before it's stable, have a look at Xyster_Container in the incubator.