cakephp 的事件系统(Getting to grips with CakePHP’s events system), 基于观察者模式
This article was written about CakePHP 2.x and has been untested with CakePHP 3.x
CakePHP seems to get a slightly unfavourable reputation when compared to the likes of Symfony orZend Framework due to its lack of namespaces and not playing nicely with Composer out of the box. However, that will change in the forthcoming version 3; and CakePHP 2 still remains a pretty easy PHP framework to work with and quickly build web applications with.
A design pattern that is pretty common in MVC applications is the Observer pattern, colloquially known as event handlers. From the Wikipedia entry, it’s defined as:
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
So plainly put: when something changes in your application, you can have code somewhere else that does something too. This makes for a better separation of concerns and more modular code that’s easier to maintain.
The events system in CakePHP
CakePHP comes with a built-in events system but it’s poorly documentated, and not the most straightforward of things based on the number of questions on Stack Overflow surrounding it. CakePHP’s implementation follows the traditional Observer pattern set-up pretty closely:
- There are subjects, which may be a model or a controller
- Subjects raise events
- An observer (or listener) is “attached” to subjects and “listens” for events to be raised
So let’s think of a scenario…
The scenario
A website that accepts user registrations. When a user registers an account is created for them, but is initially inactive. A user has to activate their account by clicking a link in an email.
One approach would be just to put the code that sends the activation email in the User
model itself:
<?php
class User extends AppModel {
public function afterSave($created, $options = array()) {
if ($created) {
$email = new CakeEmail();
$email->to($this->data[$this->alias]['email']);
$email->from(array( 'noreply@example.com' => 'Your Site' ));
$email->subject('Activate your account');
$email->format('text');
$email->template('new_user');
$email->viewVars(array( 'user' => $this->data[$this->alias] ));
$email->send();
}
}
But this is mixing concerns. We don’t want the code that sends the activation email in our User
model. The model should just deal with retrieving, saving, and deleting User
records.
So what can we do? We can implement the Observer pattern.
Raising events
First we can remove the email sending code from our afterSave()
callback method, and instead raise an event:
<?php
App::uses('CakeEvent', 'Event'); class User extends AppModel {
public function afterSave($created, $options = array()) {
if ($created) {
$event = new CakeEvent('Model.User.created', $this, array( 'id' => $this->id, 'data' => $this->data[$this->alias] ));
$this->getEventManager()->dispatch($event);
}
}
As you can see, our afterSave()
method is now much leaner.
Also note the App::uses()
statement added to the top of the file, to make sure the CakeEvent
class is imported. We’re creating an instance of the CakeEvent
event class, passing it an event name ("Model.User.created
"), a subject ($this
), and some data associated with this event. We want to pass the newly-created record’s ID, and the data of this record.
With event names in CakePHP, it’s recommended to use pseudo name-spacing. In the above example, the first portion is the tier (Model
), the second portion is the object within that tier (User
), and the third portion is a description name of the event (created
). So we know from the event name that it’s when a new user record is created.
Creating a listener
Now we have events being raised, we need code to listen for them.
The first step is to create code to do something when an event is raised. This is where CakePHP’s documentation starts getting hazy. It provides sample code, but it doesn’t tell you where to actually put it. I personally created an Event directory at the same level as Config, Controller, Model etc. I then name my class after what it’s doing. For this handler, I’m going to call itUserListener
and save it as UserListener.php.
Event listeners in CakePHP implement the CakeEventListener
interface, and as a result need to implement one method calledimplementedEvents()
. The skeleton code for the listener class then looks like this:
<?php
App::uses('CakeEventListener', 'Event'); class UserListener implements CakeEventListener {
public function implementedEvents() {
// TODO
}
}
The implementedEvents()
method expects an associative array mapping event names to methods that should handle such events. So let’s flesh that out with the one event we’re raising:
public function implementedEvents() {
return array(
'Model.User.created' => 'sendActivationEmail'
);
}
Simples.
So now, we need to actually create that sendActivationEmail()
method we’ve specified. This is where we would put the code to be ran when a user is created.
public function sendActivationEmail(CakeEvent $event) {
// TODO
}
The method is passed one argument: an instance of CakeEvent
. In fact, this would be the CakeEvent
instance you raise in yourUser
model. We set some data there (an ID and the current record’s data), and that data is now going to available to us in the instance passed to our listener method.
So now we know what we’re getting, let’s flesh our listener method out some more with that email sending code:
public function sendActivationEmail(CakeEvent $event) {
$this->User = ClassRegistry::init('User'); $activationKey = Security::generateAuthKey(); $this->User->id = $event->data['id'];
$this->User->set(array(
'active' => false,
'activation_key' => $activationKey
));
$this->User->save(); $email = new CakeEmail();
$email->from(array(
'noreply@example.com' => 'Your Site'
));
$email->to($event->data['user']['email']);
$email->subject('Activate your account');
$email->template('new_user');
$email->viewVars(array(
'firstName' => $event->data['user']['first_name'],
'activationKey' => $activationKey
));
$email->emailFormat('text');
$email->send();
}
The code above is doing the following:
- Creating an instance of the
User
model, as we don’t initially have it available in our listener class - Generating an activation key for the user
- Setting the activation key for the user in the database, whose ID we get from the event raised
- Sending the activation email, with our generated activation key
And that’s all there is to our listener class.
Because we’re using the CakeEmail
and Security
classes in CakePHP, it’s a good idea to make sure they’re loaded. At the top of the file, add these two lines:
App::uses('CakeEmail', 'Network/Email');
App::uses('Security', 'Utility');
Attaching the listener
We now have two out of three components in our Observer pattern set up: events are being raised, and we have code to act on raised events; we just need to hook the two together now. This is where CakePHP’s documentation just leaves you completely on your own.
One approach is to do this in the app/Config/bootstrap.php file. We need to create an instance of our event listener class and attach it to the User
model using its event manager.
The code is simple. At the bottom of your bootstrap.php add the following code:
App::uses('ClassRegistry', 'Utility');
App::uses('UserListener', 'Event'); $user = ClassRegistry::init('User');
$user->getEventManager()->attach(new UserListener());
As you can see, we’re using CakePHP’s ClassRegistry
utility class to load the User
model; and then using the User
model’s event manager to attach our UserListener
class. So now when the User
model fires an event, our UserListener
class (and any other listener classes attached to it) will be listening for it. Neat!
Conclusion
Hopefully you can see the merits of the Observer pattern. This is just one example; there are many other use cases where this pattern would be appropriate. Hopefully this blog post will demystify CakePHP’s implementation of this design pattern and you can find areas in your own applications where you can apply it yourself.
If you do use CakePHP’s events system in your own applications, then I’d love to see your implementations and the problems you solved using it.
cakephp 的事件系统(Getting to grips with CakePHP’s events system), 基于观察者模式的更多相关文章
- Getting to grips with CakePHP’s events system
CakePHP seems to get a slightly unfavourable reputation when compared to the likes of Symfony or Zen ...
- 主流PHP框架间的比较(Zend Framework,CakePHP,CodeIgniter,Symfony,ThinkPHP,FleaPHP)
Zend Framework 优点: Zend Framework大量应用了PHP5中面向对象的新特征:接口.异常.抽象类.SPL等等.这些东西的应用让Zend Framework具有高度的模块化和灵 ...
- CakePHP不支持path/to路径,前后台无法方法
本来想把前后台分离,可是阅读了cakephp的说明,才发现.cakephp根本就不支持path/to路径. cakephp官网给出的 管理员分离方式:http://book.cakephp.org/2 ...
- 使用GitLab CI + Capistrano部署CakePHP应用程序
使用GitLab CI + Capistrano部署CakePHP应用程序 摘要:本文描述了如使用GitLab CI + Capistrano部署CakePHP应用程序. 目录 1. 问题2. 解决方 ...
- 从CakePHP 1.3升级到2.5
从CakePHP 1.3升级到2.5 摘要:最近把一个CakePHP 1.3的项目升级到了2.x,当然就用最新的版本2.5.3了,结果基本满意.本文记录了升级的过程,包括使用的工具,遇到的问题和相应的 ...
- InnoDB与UUID
CakePHP本身有一个uuid实现,所以一直以来,我都在尝试使用uuid做主键的可能性.虽然MySQL是我最常用的数据库,但是和 auto_increment_int主键相比,我对uuid主键更有好 ...
- PHP代码审计(初级篇)
一.常见的PHP框架 1.zendframwork: (ZF)是Zend公司推出的一套PHP开发框架 功能非常的强大,是一个重量级的框架,ZF 用 100%面向对象编码实现. ZF 的组件结构独一无二 ...
- Unity3d项目入门之虚拟摇杆
Unity本身不提供摇杆的组件,开发者可以使用牛逼的EasyTouch插件或者应用NGUI实现相关的需求,下面本文通过Unity自身的UGUI属性,实现虚拟摇杆的功能. 主参考 <Unity:使 ...
- JavaScript之DOM等级概述
这两日对DOM等级的理解不是太通透,就进Mozilla官网去看了一下,然后进行了首次的对技术文档的翻译工作,虽然官网也有中文解释,但我想,自己翻译出来时,已经有了原汁原味的理解了吧,这边是做此次翻译的 ...
随机推荐
- Android 中OKHttp请求数据get和post
1:在Android Studio 的 build.gradle下 添加 然后再同步一下 compile 'com.squareup.okhttp:okhttp:2.4.0'compile 'com ...
- Python 查找binlog文件
经常需要在 binlog 中查找一些日志信息,于是写了一个简单的脚本.对于非常巨大的 binlog 文件,该脚本可能会速度慢,毕竟还是用的 list,暂时没想到好办法. 详细看代码: #/usr/bi ...
- HDU 5765 Bonds
比赛时候想了好久,不会.看了官方题解才会...... Bond是极小割边集合,去掉一个Bond之后,只会将原图分成两个连通块. 假设某些点构成的集合为 s(点集中的点进行状压后得到的一个十进制数),那 ...
- c语言-转义序列
字符组合是由反斜杠 (\) 后接字母或位组合构成的字符组合.若要显示换行符,单引号或某些其他字符在字符串末尾,必须使用转义序列. 转义序列被视为单个字符,因此,它是有效的字符常数. 转义序列通常用于指 ...
- Entity Framework技巧系列之十二 - Tip 46 - 50
提示46. 怎样使用Code-Only排除一个属性 这次是一个真正简单的问题,由StackOverflow上这个问题引出. 问题: 当我们使用Code-Only把一个类的信息告诉Entity F ...
- VituralBox 虚拟机网路设置 主机无线
主机和虚拟机都关闭防火墙 主机和虚拟机可以互相ping通 主机和虚拟机都可以联网 如果出现 ‘device not managed by NetworkManager’ 错误 network服务器 ...
- Nginx 和 IIS 实现动静分离【转载】
前段时间,搞Nginx+IIS的负载均衡,想了解的朋友,可以看这篇文章:<nginx 和 IIS 实现负载均衡>,然后也就顺便研究了Nginx + IIS 实现动静分离.所以,一起总结出来 ...
- jetty访问jsp页面出现( PWC6345: There is an error in invoking javac)
org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac. A full JDK (not ju ...
- vs远程调试
一.远程 建立共享目录debug 二.本地 1.生成->输出->输出路径,由"bin\Debug\"改为远程目录"\\xxx\\debug&quo ...
- 转 linux下xargs命令用法详解
xargs在linux中是个很有用的命令,它经常和其他命令组合起来使用,非常的灵活. xargs是给命令传递参数的一个过滤器,也是组合多个命令的一个工具.它把一个数据流分割为一些足够小的块,以方便过滤 ...