事件
作用:解耦
应用场景:用户评论
一般的用户名评论需要后台需要做三件事情(数据安全性应该除外)1.敏感词过滤
2.审核
3.发布
就拿敏感词过滤
来举例
以我目前的水平来看,我把代码的实现方法分成四种
以MVC
为例
1.数据提交的controller,所有的逻辑都在controller中实现
class IndexController extends CController{
public function actionComment()
{
//1.过滤名称对应代码
//2.写入数据库
//3.返回状态
}
}
2.数据提交的controller,过滤逻辑在model层实现
class IndexController extends CController{
public function actionComment()
{
//1.写入数据库
//过滤逻辑在Post Model中实现
$post = new post;
$post->addComment("评论内容");
//3.返回状态
}
}
3.将敏感词过滤抽象成一个类
4.敏感词过滤类结合事件
contentFilter.php
class contentFilter
{
public function filter($event)
{
echo '过滤内容'.$event->params['contents'].PHP_EOL;
}
}
post.php
class post extends CActiveRecord
{
function addComment($contents)
{
//1.文本逻辑判断(长度、字符集..)
//2.
if($this->hasEventHandler('onAddComment'))
{
$this->onAddComment($contents);
}
}
function onAddComment($contents)
{
$this->raiseEvent('onAddComment', new CEvent($this,array('contents'=>$contents)));
}
}
controller
yii::import('ext.common.*');
class IndexController extends CController{
public function actionComment()
{
$post= new post;
$post->onAddComment = array(new contentFilter,'filter');
$post->addComment("评论内容");
}
}