将Phalcon事件管理器绑定到调度程序会导致错误

时间:2015-02-02 16:36:15

标签: phalcon

我是Phalcon的新手,我试图将侦听器绑定到调度程序服务。

这是听众:

<?php

namespace Core\Listener;

use Phalcon\DI;
use Phalcon\Dispatcher;
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;

class DispatchListener extends Plugin
{

    protected $_logger;

    public function __construct()
    {
        $this->_logger = new \Phalcon\Logger\Adapter\File( 'logs/app.log' );
    }

    public function beforeDispatch ( Event $event ,  Dispatcher $dispatcher )
    {

       $this->_logger->info( 'dispatching' );

    }

    public function afterDispatch ( Event $event ,  Dispatcher $dispatcher )
    {

        $this->_logger->info( 'dispatched....' );

    }

}

还没有发生太多事情,只是试图设置。在我的bootstrap index.php中,我有:

$di = new \Phalcon\DI\FactoryDefault();

$di->set('dispatcher', function() use ($di) {

    //Obtain the standard eventsManager from the DI
    $eventsManager = $di->getShared('eventsManager');

    //Instantiate the Security plugin
    $listener = new \Core\Listener\DispatchListener($di);

    //Listen for events produced in the dispatcher using the Security plugin
    $eventsManager->attach('dispatch', $listener);

    $dispatcher = $di->getShared( 'dispatcher' );
    //Bind the EventsManager to the Dispatcher
    $dispatcher->setEventsManager($eventsManager);

    return $dispatcher;
});

现在,当我打开网站时,听众没有任何反应。没有记录,没有。我必须忽视这里显而易见的事情,但我和我一样。无法看清楚。

1 个答案:

答案 0 :(得分:1)

用精神焕发的头脑看你的代码可以做什么!我在原始问题中不仅忘记提及我正在进行模块化项目。我也忘记了我的模块是我设置调度员的地方!所以将上述代码移动到我的Module.php解决了这个问题。所以,我的Module.php现在看起来像:

<?php

namespace MyModule;

use Phalcon\Loader,
    Phalcon\Mvc\Dispatcher,
    Phalcon\Mvc\View,
    Phalcon\Mvc\ModuleDefinitionInterface;

class Module implements ModuleDefinitionInterface
{

    public function registerServices($di)
    {

        //Registering a dispatcher
        $di->set('dispatcher', function() use( $di ) {

            $dispatcher = new Dispatcher();
            $dispatcher->setDefaultNamespace('MyModule\Controller');

            /* add a listener */
            $eventsManager = $di->getShared('eventsManager');
            $listener = new \SomeModule\Listener\DispatchListener($di);
            $eventsManager->attach('dispatch', $listener);
            $dispatcher->setEventsManager($eventsManager);

            return $dispatcher;
        });
    }
}

就是这样,我的听众现在完美无缺。