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

2022-04-15 0 1,067

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

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

Yii Framework 中事件和行为的区别和应用 https://www.jb51.net/article/184208.htm

假设有类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组件的事件机制分析 https://www.jb51.net/article/184203.htm

更多关于Yii相关内容感兴趣的读者可查看本站专题

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 PHP编程 再谈Yii Framework框架中的事件event原理与应用 https://www.niceym.com/15171.html