I'm developing a PHP framework for educational purposes. I have learned a lot since I started it.
I've decided how I'm going to deal with dependencies. I'm create a simple DI Container.
My first question is not about the DI Container itself, but how to inject objects that are created outside (before the DI Container).
Q: In the example: I am calling container->manualAdd('_logger', $logger);. Is there another way to accomplish this? Am I breaking the idea of DI Container?
My second question is about hooking functions. So when in bootstrap all objects are instantiated, objects by it selves can now begin to function.
Q: In the example: I'm creating an EventDispatcher. Whoever needs to do something either on doneBuild or beforeTerminate, is injected with BootstrapEventDispatcher. Is there another way to do this?
I begin to think EventDispatcher is overkill (for bootstrap only), and maybe implement something like: CodeIgniter:Hooks
Any help is appreciated.
Example bootstrap (pseudo-code):
function bootstrap($file = 'file.xml'){
$logger = new Logger();
$logger->log('bootstrap: init');
$dispatcher = new BootstrapEventDispatcher($logger);
$container = new DIContainer(new ConfigReader($file), $logger);
$container->manualAdd('_logger', $logger);
$container->manualAdd('_bootstrap_event_dispatcher', $dispatcher);
$container->build();
$dispatcher->doneBuild(null, new EventArgs());
$dispatcher->beforeTerminate(null, new EventArgs());
$logger->log('bootstrap: terminate');
}
class DIContainer{
public function build(){
//read xmls and create classes, etc.
$this->logger->log('DIContainer: creating objects: {objects}');
}
}
Example of an xml:
<!-- example file.xml !-->
<services>
<service id="simple_class" class="SimpleClass"></service>
<service id="complex_class" class="ComplexClass">
<argument type="service" id="simple_class" /> <!-- dependency injection !-->
<argument type="service" id="_logger" /> <!-- dependency injection !-->
<argument type="service" id="_bootstrap_event_dispatcher" /> <!-- dependency injection !-->
</service>
</services>
Example of ComplexClass:
class ComplexClass{
public function __construct(SimpleClass $simpleClass, BootstrapEventDispatcher $dispatcher, Logger $logger){
$this->simpleClass = $simpleClass;
$this->logger = $logger;
$dispatcher->onDoneBuild(array($this, 'onBootstrapDoneBuild'));
}
public function onBootstrapDoneBuild($obj, $args){
//do something.
$this->logger->log('complexclass: did something');
}
}