CakePHP3:如何在helper中实现事件
在Cakephp 3中,我试图在helper类中实现事件,这是我尝试执行的示例:CakePHP3:如何在helper中实现事件,cakephp,events,cakephp-3.0,helper,Cakephp,Events,Cakephp 3.0,Helper,在Cakephp 3中,我试图在helper类中实现事件,这是我尝试执行的示例: protected $_View; public function __construct(View $View, $config = []) { //debug($View);die; $this->_View = $View; parent::__construct($View, $config); $this->_
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;
}
有可能以这种方式实现事件吗?我做错了什么 助手类已经实现了
EventlistenerInterface
,因此,如中所述,在自定义助手中,您所要做的就是从implementedEvents()
方法返回一个带有所需事件名称的正确数组到回调映射
比如:
public function implementedEvents()
{
$mapping = parent::implementedEvents();
$mapping += [
'Helper.Layout.beforeFilter' => 'someMethodOfYourHelper',
];
return $mapping;
}
警告是php中的基本类型提示。只是阅读、理解并照上面说的去做?
public function implementedEvents()
{
$mapping = parent::implementedEvents();
$mapping += [
'Helper.Layout.beforeFilter' => 'someMethodOfYourHelper',
];
return $mapping;
}