我们要在一个行为里使用htmlpurifier类,用这种行为可以加强任何模型并表明各属性我们想让它们XSS安全。
我写了以下行为:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | classCSafeContentBehaviorextendsCActiveRecordBehavior { public$attributes=array(); protected$purifier; function__construct(){ $this->purifier =newCHtmlPurifier; } publicfunctionbeforeSave($event) { foreach($this->attributesas$attribute){ $this->getOwner()->{$attribute} =$this->purifier->purify($this->getOwner()->{$attribute}); } } } |
把这个类放在你的应用程序目录,例如:application/behaviors/CSafeContentBehavior.php。现在你在模型的行为中这样去写:
| 1 2 3 4 5 6 7 8 9 10 11 12 | classPostextendsCActiveRecord { publicfunctionbehaviors(){ returnarray( 'CSafeContentBehavor'=>array( 'class'=>'application.behaviors.CSafeContentBehavior', 'attributes'=>array('title','body'), ), ); } } |
现在我们可以开始了。我们的post模型在每个保存操作中将净化标题和内容列。