`
hudeyong926
  • 浏览: 2018576 次
  • 来自: 武汉
社区版块
存档分类
最新评论

YII Behavior重用

 
阅读更多

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

 

1.CActiveRecordBehavior

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};
            $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名。可以在数据库中配置

<?php
/**
 * 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);
    }
}
?>
'behaviors' => array(
    'theme' => 'application.components.behaviors.ThemeBehavior',
    'lang'  => 'application.components.behaviors.LangBehavior',
    'module'=> 'application.components.behaviors.ModuleBehavior'
),
 上面main也可以替代index.php
$app = Yii::createWebApplication($config);
$app->attachBehavior('module','application.components.behaviors.ModuleBehavior');
在protectd/components/behaviors增加2个Behavior:
<?php
//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
<?php
//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);
    }
}
 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics