我的理解是:Behavior的目的就是重用。
当把一个Behavior加入到Component后,这个Component就有了这个Behavior的方法、属性、事件。
但是我还是搞不清楚什么时候要使用Behavior,各位大神能不能举个例子,什么时候将代码放在Behaviors里面?
附上我的代码:
<code class="lang-php"><?phpclass TestBehavior extends CBehavior{public function events(){ return array_merge(parent::events(),array( 'onClick'=>'sayHello' ));}public function sayHello(){ echo 'hello world!!!';}}?></code>
<code class="lang-php"><?phpYii::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;ch<strong style="color:transparent">本&文来源gao@daima#com搞(%代@#码网@</strong><textarea>搞gaodaima代码</textarea>arset=utf-8');// echo 'hello world';// }}?></code>
回复内容:
我的理解是:Behavior的目的就是重用。
当把一个Behavior加入到Component后,这个Component就有了这个Behavior的方法、属性、事件。
但是我还是搞不清楚什么时候要使用Behavior,各位大神能不能举个例子,什么时候将代码放在Behaviors里面?
附上我的代码:
<code class="lang-php"><?phpclass TestBehavior extends CBehavior{public function events(){ return array_merge(parent::events(),array( 'onClick'=>'sayHello' ));}public function sayHello(){ echo 'hello world!!!';}}?></code>
<code class="lang-php"><?phpYii::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';// }}?></code>
Behavior翻译成行为,行为即是方法。也就说说在Yii中,可以随意给类(必须是CComponent子类)添加类本身不存在的方法或新的方法,两个例子:
- CTimestampBehavior 这个Behavior是通过覆盖CActiveRecord的beforeSave方法来实现自动填充添加/修改时间。
- 在使用Yii上传类CUploadedFile的时候可能会遇到这样的问题:公司有自己的存储服务,那么CUploadedFile自带的保存到本地方法就不能用了。那么通过给CUploadedFile类添加一个Behavior类,在这个Behavior类里写合适当前环境的上传方式,调用的时候直接正常调用Behavior里的类,这个过程和调用CUploadedFile中的类没什么两样。
其实我用了很久也基本没接触过自己去写behavior,唯一用到的就是http://www.yiiframework.com/doc/api/1.1/CTimestampBehavior这个自带的behavior,来自动保存Model时间相关字段。因为平时满足需求就用懒得方法,没去想利用这个。