1) Ok what have we done here ?
We just create container object when we define all objects, we called them services:
private $services = ;
public function buildServices()
$classB = new ClassB('B1', 'B2');
$this->services['serviceB'] = $classB;
$classA1 = new ClassA($this->services['serviceB'], 'A1', 'A2');
$this->services['serviceA1'] = $classA1;
$classA2 = new ClassA($this->services['serviceB'], 'Different A1', 'Different A2');
$this->services['serviceA2'] = $classA2;
public function getService($serviceName)
We defined all objects and their dependencies in method "buildServices" and introduce to clients easy interface to get proper objects.
Dependency hierarchy in real world often can be defined in some nice format: xml, yaml or by annotation.
$classA1 = $container->getService('serviceA1');
$classA2 = $container->getService('serviceA2');
2) What are advantages of this solution?
- we have in one place defined clear structure of dependency
- we can easily create full customizable objects
- clients are really simple, aren't they ?
It's very powerful design pattern.