Cakephp 3:如何在助手中实现事件

Cakephp 3: how to implement events in helper

在 Cakephp 3 中我试图在助手 class 中实现事件,这是我试图做的事情的例子:

protected $_View;

    public function __construct(View $View, $config = [])
    {
        //debug($View);die;
        $this->_View = $View;

        parent::__construct($View, $config);
        $this->_setupEvents();
    }

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

        foreach ($events as $callable) {
                $this->_View->eventManager()->on("Helper.Layout.beforeFilter", $callable);
        }
    }

    public function filter(&$content, $options = array()) {
            preg_match_all('/\[(menu|m):([A-Za-z0-9_\-]*)(.*?)\]/i', $content, $tagMatches);
            for ($i = 0, $ii = count($tagMatches[1]); $i < $ii; $i++) {
                    $regex = '/(\S+)=[\'"]?((?:.(?![\'"]?\s+(?:\S+)=|[>\'"]))+.)[\'"]?/i';
                    preg_match_all($regex, $tagMatches[3][$i], $attributes);
                    $menuAlias = $tagMatches[2][$i];
                    $options = array();
                    for ($j = 0, $jj = count($attributes[0]); $j < $jj; $j++) {
                            $options[$attributes[1][$j]] = $attributes[2][$j];
                    }
                    $content = str_replace($tagMatches[0][$i], $this->menu($menuAlias, $options), $content);
            }
            return $content;
    }

但是我在调​​用父 Helper 的构造函数的行收到警告 class:

Warning (4096): Argument 1 passed to App\View\Helper\MenusHelper::__construct() must be an instance of App\View\Helper\View, instance of App\View\AppView given, called in C:\wamp\www\CookieCMS\vendor\cakephp\cakephp\src\View\HelperRegistry.php on line 142 and defined [APP/View\Helper\MenusHelper.php, line 26]

是否可以通过这种方式在 helper 中实现事件,我做错了什么?

Helper class 已经实现了 EventlistenerInterface,因此如 manual 中所述,您在自定义帮助程序中所要做的就是 return一个适当的数组,其中包含从 implementedEvents() 方法回调映射所需的事件名称。

所以像这样:

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

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

    return $mapping;
}