cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

[BUG] Initializer isn't invoked if has been dispatcher call before.

Open iforp opened this issue 13 years ago • 6 comments

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

iforp avatar Jul 05 '13 11:07 iforp

Confirmed, looking into this.

ghost avatar Jul 05 '13 13:07 ghost

Same happens with $this->getDI()->getShared('dispatcher');

ghost avatar Jul 05 '13 13:07 ghost

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

ghost avatar Jul 05 '13 13:07 ghost

Looks like I have found the bug:

  • Phalcon\Dispatcher::dispatch() uses $di->getShared() to get the handler class; at this pont $di->_freshInstance is 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 _freshInstance to 0;
  • dispatch() then receives the control back and calls wasfreshinstance() 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.

ghost avatar Jul 05 '13 14:07 ghost

Thanks for your help

iforp avatar Jul 05 '13 14:07 iforp

This was fixed by @sjinks in 1.2.0 branch, thanks

ghost avatar Jul 06 '13 18:07 ghost