【问题标题】:Cakephp 3: how to implement events in helperCakephp 3:如何在助手中实现事件
【发布时间】:2016-02-24 21:57:00
【问题描述】:

在 Cakephp 3 中,我试图在辅助类中实现事件,这是我尝试做的示例:

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 类的构造函数的行收到警告:

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]

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

【问题讨论】:

标签: cakephp events cakephp-3.0 helper


【解决方案1】:

Helper 类已经实现了EventlistenerInterface,因此正如manual 中所解释的,您在自定义帮助程序中所要做的就是返回一个正确的数组,其中包含所需的事件名称到来自implementedEvents() 方法的回调映射。

比如:

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

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

    return $mapping;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多