Chinaunix首页 | 论坛 | 博客
  • 博客访问: 892259
  • 博文数量: 91
  • 博客积分: 803
  • 博客等级: 准尉
  • 技术积分: 1051
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-24 13:42
文章分类

全部博文(91)

文章存档

2021年(1)

2020年(4)

2019年(4)

2018年(9)

2017年(11)

2016年(11)

2015年(6)

2014年(3)

2013年(28)

2012年(14)

分类: 系统运维

2012-09-05 15:55:41

YII中的CComponent,CEvent与Behavior及CActiveRecordBehavior

完成如下功能,一个JTool类,继承CComponent,当其长度改变时,调用事件,输出"change me".

JTool.php在protected/components 下

  1. class JTool extends CComponent{  
  2. private $_width;  
  3. public function getWidth(){  
  4. return $this->_width ? $this->_width : 1;   
  5. }  
  6.   
  7. public function setWidth($width){  
  8. if($this->hasEventHandler('onChange')){  
  9. $this->onChange(new CEvent());  
  10. }  
  11. $this->_width = $width;  
  12. }  
  13.   
  14. public function onChange($event){  
  15. $this->raiseEvent('onChange'$event);  
  16. }  
  17.   
  18. }  

OK,功能已经实现了,找个控制器,执行

  1. $j = new JTool();  
  2. $j->onChange = array($this"showChange"); //给事件绑定handle showChange  
  3. $j->width = 100; //调用setWidth,解发绑定的事件showChange  
  4. function showChange(){  
  5. echo 'changed me';  
  6. }  


现在我们想给JTool添加一个功能,返回长度的100倍,我们可以继承JTool.php写一个方法

  1. class JToolSub extends JTool{  
  2. public function get100width(){  
  3. return $this->width*100;  
  4. }  
  5. }  

OK,功能实现了,这个执行就简单了new JToolSub调用方法即可





上边的这两种办法,就是仅完成功能,下边演示Behavior及events来实现

如何用Behavior来实现上边的增加一个方法,返回长度的100倍的功能呢?
写类JBe
JBe.php在protected/behavior 下

  1. class JBe extends CBehavior{  
  2.   
  3. public function get100width(){  
  4. return $this->Owner->width*100;  
  5. }  
  6. }  

OK,功能已经实现了,找个控制器,执行

  1. $j = new JTool();  
  2. $j->attachBehavior('JBe''application.behavior.JBe');  
  3. echo $j->get100width();  


如何用Behavior实现JTool中的长度改变时,调用一个事件的功能呢?
写类JBe

  1. class JBe extends CBehavior{  
  2. public function events(){  
  3. return array_merge(parent::events(),array(  
  4. 'onChange'=>'change',  
  5. ));  
  6. }  
  7.   
  8. public function change(){  
  9. echo 'changed';  
  10. }  
  11.   
  12. public function get100width(){  
  13. return $this->Owner->width*100;  
  14. }  
  15. }  

OK,功能实现随便找个控制器,执行
  1. $j = new JTool();  
  2. $j->attachBehavior('JBe''application.behavior.JBe');  
  3. $j->width = 100;  

这里的要点是events方法
返回的数组array('onChange'=>'change')定义了事件(event)和对应的事件处理方法(event hander)

事件是是Compents(JTool中)定义的,即JTool中的onChange
处理方法同由Behavior(JBe中)类定义的,即JBe中的change

这样子再看CActiveRecordBehavior,其是绑定给CActiveRecord 这个组件的,绑定方法重写behaviors()
CActiveRecordBehavior中的events() 方法返回事件及事处理函数的对应,如:
'onBeforeSave'=>'beforeSave'

即组件CActiveRecord中的onBeforeSave这个事件对应的处理函数是
CActiveRecordBehavior中的beforeSave方法

这样子CActiveRecord在调用save()时,触发事件onBeforeSave,调用CActiveRecordBehavior对应的处理函数beforeSave
我们只要写一个CActiveRecordBehavior的子类,重写其中的beforeSave,执行一些操作,然后给CActiveRecord绑定即可
阅读(2860) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~