再谈Yii Framework框架中的事件event原理与应用

2022-10-07,,,,

本文实例讲述了yii framework框架中的事件event原理与应用。分享给大家供大家参考,具体如下:

再谈yii framework中的事件event,我写过的关于yii事件event的另一篇文章

yii framework 中事件和行为的区别和应用

假设有类mycomponent,它是继承于ccomponent,通过查看 ccomponent 的 __set() 方法,

public function __set($name,$value)
{
  $setter='set'.$name;
  if(method_exists($this,$setter))
    return $this->$setter($value);
  else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
  {
    // duplicating geteventhandlers() here for performance
    $name=strtolower($name);
    if(!isset($this->_e[$name]))
      $this->_e[$name]=new clist;
    return $this->_e[$name]->add($value);
  }
  else if(is_array($this->_m))
  {
    foreach($this->_m as $object)
    {
      if($object->getenabled() && (property_exists($object,$name) || $object->cansetproperty($name)))
        return $object->$name=$value;
    }
  }
  if(method_exists($this,'get'.$name))
    throw new cexception(yii::t('yii','property "{class}.{property}" is read only.',
      array('{class}'=>get_class($this), '{property}'=>$name)));
  else
    throw new cexception(yii::t('yii','property "{class}.{property}" is not defined.',
      array('{class}'=>get_class($this), '{property}'=>$name)));
}

第四行可知,我们可以通过 onxxx 来直接设置事件的。

绑定到全局事件处理

方法一:

直接在main.php里面定义

/***************************************************
在我们想要的内容的前后出现了这些代码
只是为了说明,我们添加的内容是要放在
这个配置数据的一维里面。
'import'=>array(
  'application.models.*',
  'application.components.*',
  'application.helpers.*',
),
'defaultcontroller'=>'post',
***************************************************/

//其它代码
'import'=>array(
  'application.models.*',
  'application.components.*',
  'application.helpers.*',
),

/************** 这才是我们想要添加的代码 **************/
'onbeginrequest' => array('myeventhandler', 'myeventhandlermethod'),

'defaultcontroller'=>'post',
//其它代码

方法二:

//参考自framework/logging/clogrouter.php的init()方法
yii::app()->attacheventhandler('onendrequest',array($this,'processlogs'));

绑定到局部事件处理

随时随地无论在controller还是model里面,只要是ccomponent的子类,都可以这样定义,

$mycomponent->onclick = $callback;

这里的 $callback 指向了一个有效的 php 回调。它可以是一个全局函数也可以是类中的一个方法。

如果是后者,它必须以一个数组的方式提供 : array($object,'methodname')

其它文章推荐:

yii组件的事件机制分析

《再谈Yii Framework框架中的事件event原理与应用.doc》

下载本文的Word格式文档,以方便收藏与打印。