[BUG] Initializer isn't invoked if has been dispatcher call before.
Phalcon 1.2.0.BETA.2 - Windows x86 for PHP 5.4.0
<?php
class MainTask extends \Phalcon\CLI\Task
{
public function beforeExecuteRoute() {
// $this->dispatcher;
echo __METHOD__, PHP_EOL;
}
public function initialize() {
echo __METHOD__, PHP_EOL;
}
public function mainAction(){}
}
$di = new Phalcon\DI\FactoryDefault\CLI;
$di->setShared('dispatcher', function() use ($di)
{
$dispatcher = new Phalcon\CLI\Dispatcher;
$dispatcher->setDI($di);
return $dispatcher;
});
$console = new Phalcon\CLI\Console;
$console->setDI($di);
$console->handle();
output is
MainTask::beforeExecuteRoute MainTask::initialize
I can't understand the reasons, but if you uncomment this line, then the initializer is not called // $this->dispatcher;
and output would be
MainTask::beforeExecuteRoute
Confirmed, looking into this.
Same happens with $this->getDI()->getShared('dispatcher');
This seems to solve the issue:
diff --git a/ext/di.c b/ext/di.c
index bf520ac..00936ed 100644
--- a/ext/di.c
+++ b/ext/di.c
@@ -450,7 +450,7 @@ PHP_METHOD(Phalcon_DI, getShared){
if (phalcon_array_isset(shared_instances, name)) {
PHALCON_OBS_VAR(instance);
phalcon_array_fetch(&instance, shared_instances, name, PH_NOISY_CC);
- phalcon_update_property_bool(this_ptr, SL("_freshInstance"), 0 TSRMLS_CC);
} else {
/**
* Resolve the instance normally
Looks like I have found the bug:
- Phalcon\Dispatcher::dispatch() uses
$di->getShared()to get the handler class; at this pont$di->_freshInstanceis true; - dispatch:beforeExecuteRoute is fired and
MainTask::beforeExecuteRoute()is invoked; - it then tries to get the dispatcher by (directly or indirectly)
$this->getDI()->getShared('dispatcher'); getShared()notices that the dispatcher is already initialized and sets_freshInstanceto 0;dispatch()then receives the control back and callswasfreshinstance()on the DI;- DI returns false because the latest queries service was the dispatcher, not the handler class;
- and because of this initialize() is not called.
My suggestion is to check wasfreshinstance() right after the handler class has been successfully queried.
Thanks for your help
This was fixed by @sjinks in 1.2.0 branch, thanks