-
Notifications
You must be signed in to change notification settings - Fork 1
Dependency_injection
Jonathan Hawk edited this page Jun 27, 2015
·
1 revision
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 PHP Dependency Injection container. Here's an example of how you might use the container. (This example is adapted into PHP 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->autowire("Apple");
$container->autowire("Juicer");
$container->autowire("Peeler");
Get component with dependencies injected:
$juicer = $container->get("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
.