行为Behavior的使用

原文地址:http://www.it610.com/article/4918541.htm

行为就是继承yii\base\behavior,可以绑定到任意yii\base\compent实例上,然后这个compent实例就拥有了行为类所具有的属性和方法;

注意:Behavior只能与Component类绑定

参考出处:http://www.digpage.com/behavior.html

下面是两个例子:

1、分别定义行为类MyBehavior.php和组件类MyBehaviorAttachClass.php

(1)MyBehavior.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace app\models;
use yii\base\Behavior;
?>
<?
class MyBehavior extends Behavior
{
    public $propertyTest='this is MyBehavior propertyTest';
    public function methodTest()
    {
        echo 'this is MyBehavior methodTest';
    }
 
}
?>

(2)MyBehaviorAttachClass.php

1
2
3
4
5
6
7
8
9
10
<?php
namespace app\models;
use yii\base\component;
?>
<?
class MyBehaviorAttachClass extends component
{
 
}
?>

(3)控制器中写个方法,以便演示时调用

1
2
3
4
5
6
7
8
public function actionBehavior()
    {
        $MyBehavior=new MyBehavior;
        $MyBehaviorAttachClass=new MyBehaviorAttachClass;
        $MyBehaviorAttachClass->attachBehavior('MyBehavior',$MyBehavior);
        echo $MyBehaviorAttachClass->propertyTest;
        echo $MyBehaviorAttachClass->methodTest();
    }

此时运行r=hello/Behavior就会显示如下界面:

行为Behavior的使用

2、在ActiveRecord中调用行为,这种属于静态调用,直接在类中写个behaviors方法就可以了

详情看:http://www.yiichina.com/question/807

下面是gii_test.php,位于models下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class gii_test extends \yii\db\ActiveRecord
{
    
public function behaviors()
{
return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],//其中created_at和updated_at是gii_test数据表的字段名,必须设置为int才能显示时间戳
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],//否则显示00000000
                ],
            ],
        ];
   }
}

如果需要保留字段属性为 timestamp ,可以使用如下方法自动填充:

1
2
3
4
5
6
7
8
9
10
11
12
use yii\db\Expression;
public function behaviors()
{
     return [
         [
             'class' => TimestampBehavior::className(),
             'createdAtAttribute' => 'created_at',
             'updatedAtAttribute' => 'updated_at',
             'value' => new Expression('NOW()'),
         ],
     ];
}
上一篇:hadoop2.2编程:自定义hadoop map/reduce输入文件切割InputFormat


下一篇:MySQL:数据查询