首页 > 活着 > YII Behavior重用

YII Behavior重用

用behavior的好处是可以通过“插入”的方式来获得新的功能。你当然可以直接把代码写在model里。不过如果类似的代码需要在若干个model里实现,那么behavior就可以让你重用这段代码 。

1.CActiveRecordBehavior

yii框架已经提供了一个CTimestampBehavior 行为类,只要设置好createAttribute和updateAttribute两个属性,,它分别对应你数据库表的创建时间和更新时间字段。像创建一篇文章时我们通常都会需要记录创建时间,更新时记录它的更新时间,详细使用,在你的Model类中behaviors 方法中增加下面几行, 将 createAttribute和updateAttribute更改为你数据库对应的时间字段即可:

Java代码
1.public function behaviors(){
2. return array(
3. ‘CTimestampBehavior’ => array(
4. ‘class’ => ‘zii.behaviors.CTimestampBehavior’,
5. ‘createAttribute’ => ‘create_time_attribute’,
6. ‘updateAttribute’ => ‘update_time_attribute’,
7. )
8. );
9.}
public function behaviors(){
return array(
‘CTimestampBehavior’ => array(
‘class’ => ‘zii.behaviors.CTimestampBehavior’,
‘createAttribute’ => ‘create_time_attribute’,
‘updateAttribute’ => ‘update_time_attribute’,
)
);
}XSS安全模式类

在这篇文章里,我们将描述一个基于WEB应用下避免不合法的内容注入。

我们要在一个行为里使用htmlpurifier 类,用这种行为可以加强任何模型并表明各属性我们想让它们XSS安全。

我写了以下行为:

Java代码
1. 2.class CSafeContentBehavior extends CActiveRecordBehavior
3.{
4. public $attributes =array();
5. protected $purifier;
6.
7. function __construct(){
8. $this->purifier = new CHtmlPurifier;
9. }
10.
11. public function beforeSave($event)
12. {
13. foreach($this->attributes as $attribute){
14. $this->getOwner()->{$attribute} = $this->purifier->purify($this->getOwner()->{$attribute});
15. }
16. }
17.}
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。现在你在模型的行为中这样去写:

Java代码
1. 2.class Post extends CActiveRecord
3.{
4. public function behaviors(){
5. return array(
6. 'CSafeContentBehavor' => array(
7. ‘class’ => ‘application.behaviors.CSafeContentBehavior’,
8. ‘attributes’ => array(‘title’, ‘body’),
9. ),
10. );
11. }
12.}
class Post extends CActiveRecord
{
public function behaviors(){
return array(
'CSafeContentBehavor' => array(
‘class’ => ‘application.behaviors.CSafeContentBehavior’,
‘attributes’ => array(‘title’, ‘body’),
),
);
}
}现在我们可以开始了。我们的post模型在每个保存操作中将净化标题和内容列。

保存一条记录后,更新订单号,适合所有订单号

Java代码
1. 2.class No13Behavior extends CActiveRecordBehavior {
3. public $pk = '';
4. public $orderNo = '';
5. public $prefix = '';
6.
7. public function afterSave($event) {
8. if ($this->getOwner()->getIsNewRecord()) {
9. if (empty($this->pk) || empty($this->orderNo) || empty($this->prefix)) {
10. return false;
11. }
12. $id = $this->getOwner()->{$this->pk};
13. $val = $this->prefix . date(‘ymd’) . str_pad($id, 5, ‘0’, STR_PAD_LEFT);
14. $this->getOwner()->updateByPk($id, array($this->orderNo =>$val) );
15. }
16. }
17.}
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};
$val = $this->prefix . date(‘ymd’) . str_pad($id, 5, ‘0’, STR_PAD_LEFT);
$this->getOwner()->updateByPk($id, array($this->orderNo =>$val) );
}
}
} 2.CBehavior

自动导入module模块,config/main的modules不需要加对应的module名。可以在数据库中配置

Java代码
1. 2./**
3. * ApplicationConfigBehavior is a behavior for the application.
4. * It loads additional config parameters that cannot be statically
5. * written in config/main
6. */
7.class ModuleBehavior extends CBehavior {
8. /**
9. * Declares events and the event handler methods
10. * See yii documentation on behavior
11. */
12. public function events() {
13. return array_merge(parent::events(), array(
14. 'onBeginRequest' => ‘beginRequest’,
15. ));
16. }
17.
18. /**
19. * Load configuration that cannot be put in config/main
20. */
21. public function beginRequest() {
22. $modules = array();
23. $model = Module::model()->findAll(); // Todo – should be per application
24. foreach ($model as $item) {
25. $modules[$item->name] = array(); // Todo can set parameters here for each module…
26. }
27. //$modules[‘video’] = array();
28. Yii::app()->setModules($modules);
29. }
30.}
31.?>
/**
* ApplicationConfigBehavior is a behavior for the application.
* It loads additional config parameters that cannot be statically
* written in config/main
*/
class ModuleBehavior 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代码
1.’behaviors’ => array(
2. ‘theme’ => ‘application.components.behaviors.ThemeBehavior’,
3. ‘lang’ => ‘application.components.behaviors.LangBehavior’,
4. ‘module’=> ‘application.components.behaviors.ModuleBehavior’
5.),
‘behaviors’ => array(
‘theme’ => ‘application.components.behaviors.ThemeBehavior’,
‘lang’ => ‘application.components.behaviors.LangBehavior’,
‘module’=> ‘application.components.behaviors.ModuleBehavior’
), 上面main也可以替代index.php
Java代码
1.$app = Yii::createWebApplication($config);
2.$app->attachBehavior(‘module’,’application.components.behaviors.ModuleBehavior’);
$app = Yii::createWebApplication($config);
$app->attachBehavior(‘module’,’application.components.behaviors.ModuleBehavior’);在protectd/components/behaviors增加2个Behavior:
Java代码
1. 2.//ThemeBehavior.php
3.class ThemeBehavior extends CBehavior {
4. const COOKIE_KEY = '__theme';
5.
6. public function events() {
7. return array_merge(parent::events(), array(
8. 'onBeginRequest' => ‘beginRequest’,
9. ));
10. }
11.
12. public function beginRequest() {
13. $v = Yii::app()->request->getParam(self::COOKIE_KEY);
14. if (!isset($v)) {
15. $v = Yii::app()->request->cookies[self::COOKIE_KEY];
16. if (!isset($v)) {
17. $v = Yii::app()->theme->name;
18. } else {
19. $v = $v->value;
20. }
21. }
22. Yii::app()->theme = $v;
23. Yii::app()->request->cookies[self::COOKIE_KEY] = new CHttpCookie(self::COOKIE_KEY, $v);
24. }
25.}
//ThemeBehavior.php
class ThemeBehavior extends CBehavior {
const COOKIE_KEY = '__theme';

public function events() {
return array_merge(parent::events(), array(
'onBeginRequest' => ‘beginRequest’,
));
}

public function beginRequest() {
$v = Yii::app()->request->getParam(self::COOKIE_KEY);
if (!isset($v)) {
$v = Yii::app()->request->cookies[self::COOKIE_KEY];
if (!isset($v)) {
$v = Yii::app()->theme->name;
} else {
$v = $v->value;
}
}
Yii::app()->theme = $v;
Yii::app()->request->cookies[self::COOKIE_KEY] = new CHttpCookie(self::COOKIE_KEY, $v);
}
}LangBehavior.php
Java代码
1. 2.//LangBehavior.php
3.class LangBehavior extends CBehavior {
4. const COOKIE_KEY = '__lang';
5.
6. public function events() {
7. return array_merge(parent::events(), array(
8. 'onBeginRequest' => ‘beginRequest’,
9. ));
10. }
11.
12. public function beginRequest() {
13. $v = Yii::app()->request->getParam(self::COOKIE_KEY);
14. if (!isset($v)) {
15. $v = Yii::app()->request->cookies[self::COOKIE_KEY];
16. if (!isset($v)) {
17. $v = Yii::app()->language;
18. } else {
19. $v = $v->value;
20. }
21. }
22. Yii::app()->language = $v;
23. Yii::app()->request->cookies[self::COOKIE_KEY] = new CHttpCookie(self::COOKIE_KEY, $v);
24. }
25.}
//LangBehavior.php
class LangBehavior extends CBehavior {
const COOKIE_KEY = '__lang';

public function events() {
return array_merge(parent::events(), array(
'onBeginRequest' => ‘beginRequest’,
));
}

public function beginRequest() {
$v = Yii::app()->request->getParam(self::COOKIE_KEY);
if (!isset($v)) {
$v = Yii::app()->request->cookies[self::COOKIE_KEY];
if (!isset($v)) {
$v = Yii::app()->language;
} else {
$v = $v->value;
}
}
Yii::app()->language = $v;
Yii::app()->request->cookies[self::COOKIE_KEY] = new CHttpCookie(self::COOKIE_KEY, $v);
}
}

用behavior的好处是可以通过“插入”的方式来获得新的功能。你当然可以直接把代码写在model里。不过如果 […]

  1. 还没有评论
评论提交中, 请稍候...

留言

(Spamcheck Enabled)

Trackbacks & Pingbacks ( 0 )
  1. 还没有 trackbacks