我的理解是:Behavior的目的就是重用。
当把一个Behavior加入到Component后,这个Component就有了这个Behavior的方法、属性、事件。
但是我还是搞不清楚什么时候要使用Behavior,各位大神能不能举个例子,什么时候将代码放在Behaviors里面?
附上我的代码:
<?php
class TestBehavior extends CBehavior{
public function events(){
return array_merge(parent::events(),array(
'onClick'=>'sayHello'
));
}
public function sayHello(){
echo 'hello world!!!';
}
}
?>
<?php
Yii::import('ext.behaviors.*');
class UserController extends Controller{
// public function actionGet(){
// $com=Yii::createComponent('application.components.TestComponent');
// echo $com->getName();
// }
// public function actionEvent(){
// $com=Yii::createComponent('application.components.TestComponent');
// $com->onClick=array($this,'sayHello');//调用了一个不存在属性,会使用魔术方法
// $com->onClick(new CEvent($com));
// }
public function actionBehavior(){
$com=Yii::createComponent('application.components.TestComponent');
$com->attachBehavior('test','ext.behaviors.TestBehavior');
$com->sayHello();
$com->onClick(new CEvent($com)); //behavior 中的seyHello绑定了onClick。调用onClick就会调用sayHello()
}
// public function sayHello(){
// header('Content-type:text/html;charset=utf-8');
// echo 'hello world';
// }
}
?>
Behavior翻译成行为,行为即是方法。也就说说在Yii中,可以随意给类(必须是CComponent子类)添加类本身不存在的方法或新的方法,两个例子: