调用从另一个类在helper中实现的回调

时间:2016-02-14 16:27:10

标签: cakephp events cakephp-3.0

这就是我的助手的样子:

public function implementedEvents()
{
        $mapping = parent::implementedEvents();

        $mapping += [
            'Helper.Layout.beforeFilter' => 'filter',
        ];

        return $mapping;
}

public function filter(&$content, $options = array()) {
     ...       
}

我想从另一个类调用这些回调:

$event = new Event('Helper.Layout.beforeFilter', $View, [
      'content' => &$body,
      'options' => array()
]);
EventManager::instance()->dispatch($event);

所以我需要在全局的某个地方注册在帮助器中实现的这些监听器,我该怎么做?

1 个答案:

答案 0 :(得分:0)

这就是我最后在助手课中所做的:

public function __construct(View $view, array $config = [])
{
        parent::__construct($view, $config);
        $this->_converter = new StringConverter();
        $this->_setupEvents();
}

然后我向全球事件管理员注册我的听众:

protected function _setupEvents() {
        $events = [
            'filter' => [$this, 'filter']
        ];

        foreach ($events as $callable) {
                EventManager::instance()->on("Helper.Layout.beforeFilter", $callable);
}

public function filter($event) {
 ...
}
相关问题