我试图在helper类中实现事件,这是我试图做的例子:
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]
是否有可能以这种方式在助手中实现事件以及我做错了什么?
答案 0 :(得分:2)
Helper
类已经实现了EventlistenerInterface
,因此正如manual中所解释的那样,您需要在自定义帮助程序中执行的操作是返回一个具有所需事件名称的正确数组以进行回调映射来自implementedEvents()
方法。
类似于:
public function implementedEvents()
{
$mapping = parent::implementedEvents();
$mapping += [
'Helper.Layout.beforeFilter' => 'someMethodOfYourHelper',
];
return $mapping;
}