Yii使用Component和行为

时间:2015-05-26 09:56:42

标签: php yii components behavior

如何使用Component以及每个模型和控制器使用的通用函数以及行为?

1 个答案:

答案 0 :(得分:0)

//your behavior    
class TestBehavior extends CActiveRecordBehavior
    {
        public $a = '';
        public $b = '';

        public function getA(){
            return $this->a;    
        }

        public function getB(){
            return $this->b;
        }    
        ... 
    }

//in your model
public function behaviors(){
        return array(
            'TestBehavior' => array(
                'class' => 'TestBehavior',
                'a' => 'value a ',
                'b' => 'value b',
            ),
            //one more behavior
        );
    }
...
// use model behavior:
echo $model->TestBehavior->getA();

// in controller you can use attachBehavior() it will be like:
$this->attachBehavior('TestBehavior', array(
      'class' => 'TestBehavior',
));

希望这对你有所帮助。