下面举个简单的对数据库更新和插入时间的可重用的例子
yii框架已经提供了一个CTimestampBehavior 行为类,只要设置好createAttribute和updateAttribute两个属性,,它分别对应你数据库表的创建时间和更新时间字段。像创建一篇文章时我们通常都会需要记录创建时间,更新时记录它的更新时间,详细使用,在你的Model类中behaviors方法中增加下面几行, 将createAttribute和updateAttribute更改为你数据库对应的时间字段即可:
public function behaviors(){
return array(
'CTimestampBehavior' => array(
'class' => 'zii.behaviors.CTimestampBehavior',
'createAttribute' => 'create_time_attribute',
'updateAttribute' => 'update_time_attribute',
)
);
}
XSS安全模式类
在这篇文章里,我们将描述一个基于WEB应用下避免不合法的内容注入。
我们要在一个行为里使用htmlpurifier 类,用这种行为可以加强任何模型并表明各属性我们想让它们XSS安全。
我写了以下行为:
<?php
class CSafeContentBehavior extends CActiveRecordBehavior
{
public $attributes =array();
protected $purifier;
function __construct(){
$this->purifier = new CHtmlPurifier;
}
public function beforeSave($event)
{
foreach($this->attributes as $attribute){
$this->getOwner()->{$attribute} = $this->purifier->purify($this->getOwner()->{$attribute});
}
}
}
把这个类放在你的应用程序目录,例如:application/behaviors/CSafeContentBehavior.php。现在你在模型的行为中这样去写:
<?php
class Post extends CActiveRecord
{
public function behaviors(){
return array(
'CSafeContentBehavor' => array(
'class' => 'application.behaviors.CSafeContentBehavior',
'attributes' => array('title', 'body'),
),
);
}
}
现在我们可以开始了。我们的Post模型在每个保存操作中将净化标题和内容列。
保存一条记录后,更新订单号,适合所有订单号
<?php
class No13Behavior extends CActiveRecordBehavior
{
public $pk = '';
public $orderNo = '';
public $prefix = '';
public function afterSave($event)
{
if ($this->getOwner()->getIsNewRecord()){
if(empty($this->pk)||empty($this->orderNo)||empty($this->prefix)){
return false;
}
$id = $this->getOwner()->{$this->pk};
$model = $this->getOwner()->findByPk($id);
$model->{$this->orderNo} = $this->prefix . date('ymd') . str_pad($id, 5, '0', STR_PAD_LEFT);
$model->save();
}
}
}
自动导入module模块
<?php
/**
* ApplicationConfigBehavior is a behavior for the application.
* It loads additional config parameters that cannot be statically
* written in config/main
*/
class ApplicationConfigBehavior extends CBehavior
{
/**
* Declares events and the event handler methods
* See yii documentation on behavior
*/
public function events()
{
return array_merge(parent::events(), array(
'onBeginRequest'=>'beginRequest',
));
}
/**
* Load configuration that cannot be put in config/main
*/
public function beginRequest()
{
$modules = array();
$model = Module::model()->findAll(); // Todo - should be per application
foreach ($model as $item)
{
$modules[$item->name] = array();// Todo can set parameters here for each module...
}
//$modules['video'] = array();
Yii::app()->setModules($modules);
}
}
?>
Main.php代码
'behaviors' => array('application.components.behaviors.ApplicationConfigBehavior'),
