事件系统在一个程序中能起到非常大的作用,它可以使你的代码松散耦合,轻松的和其他模块通信,而不必硬编码.在cakephp中就自带了事件系统.
创建一个事件
use Cake\Event\Event;
$event = new Event($name, $subject, $data);
Event参数
name 事件名称 例如 Dao.testEvent
subject 将该事件应用于对象(通常是生成事件的对象)如 null,$this
data 事件的数据,侦听器可以获得该数据
发布一个事件
//在controller 中
$this->eventManager()->dispatch($event);
到这里事件就已经发布出去了,如果需要对这事件需要响应,比如一个用户注册事件,当事件发出后,自动发送欢迎邮件,那么就需要创建一个侦听器.
创建一个事件侦听器
use Cake\Event\EventListenerInterface;
class testEventListener implements EventListenerInterface
{
/**
* 返回监听事件
**/
public function implementedEvents()
{
return [
'Dao.testEvent' =>array(
'callable'=>array($this,'sendEmail')
)
];
}
public function sendEmail($event)
{
}
}
注册事件侦听器
将以下代码加入 /config/bootstrap.php
use Cake\Event\EventManager;
$addon = new testEventListener();
EventManager::instance()->on($addon);
完成
Congratulations @jieao! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
You published your First Post
You made your First Vote
You got a First Vote
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @jieao! You have received a personal award!
1 Year on Steemit
Click on the badge to view your Board of Honor.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @jieao! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit