我们经常要对用户输入的内容进行过滤处理,比如过滤不文明内容,这种情况下,我们可以考虑使用行为机制处理.
1.先定义一个html过滤行为类
在protected/behavior/下建立myHtmlFilter.php文件。代码如下
<?php
/**
*定义一个标签过滤行为
*/
class myHtmlFilter extends CBehavior {
public $strip_tags = false ;
//绑定事件。如果绑定了这个行为的组件触发了filter事件,将自动运行filterHtml方法
public function events() {
return array(
'onfilter' => 'filterHtml',
);
}
public function filterHtml($event) {
//下面的判断可以根据实际情况改变.主要看输入对象类的父类是哪一个
if($event->sender instanceof CActiveRecord) {//事件发起者判断,如果事件是由 CFormModel 对象发起....
$input = $event->sender->attributes ;
$event->sender->attributes = $this->filterbadword($input);
}
}
//过滤不文明字
public function filterbadword(&$data){
//这只是简单的判断,可以读取数据库不文明字体进行过滤
$badword=array('你妈的','狗屁','傻B','禽兽');
if(is_array($data))
{
foreach($data as $k1=>$v1)
{
if(is_array($v1))
$data[$k1]=filterbadword($v1);
else
$data[$k1]=str_replace($badword,'****',$v1);
}
}
else {
$data=str_replace($badword,'****',$data);
}
return $data;
}
}
?>
2.绑定行为,使用行为。
下面是用yii gii crud生成的控制器的一部分代码
public function actionCreate()
{
$model=new News;
if(isset($_POST['News']))
{
$model->attributes=$_POST['News'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
更改以上代码实现过滤
public function actionCreate()
{
Yii::import('application.behavior.myHtmlFilter');
$model=new News;
if(isset($_POST['News']))
{
$model->attributes=$_POST['News'];
//给$model组件绑定myHtmlFilter行为
$model->attachBehavior('myFilter', array(
'class' => 'myHtmlFilter',
'strip_tags' => true ,//给行为中的$strip_tags属性赋默认值
));
//触发$model中的onfilter事件。这个时候行为中的filterHtml方法将自动调用
$model->onfilter(new CEvent($model) ) ;
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
3.为组件添加事件。找到2中News表对应的模型类文件News.php(也是用gii生成的)。添加事件
public function onfilter($event)
{
$this->raiseEvent('onfilter', $event);
}