再谈Yii Framework框架中的事件event原理与应用
本文实例讲述了YiiFramework框架中的事件event原理与应用。分享给大家供大家参考,具体如下:
再谈YiiFramework中的事件event,我写过的关于Yii事件event的另一篇文章
YiiFramework中事件和行为的区别和应用https://www.nhooo.com/article/184208.htm
假设有类MyComponent,它是继承于CComponent,通过查看CComponent的__set()方法,
publicfunction__set($name,$value)
{
$setter='set'.$name;
if(method_exists($this,$setter))
return$this->$setter($value);
elseif(strncasecmp($name,'on',2)===0&&method_exists($this,$name))
{
//duplicatinggetEventHandlers()hereforperformance
$name=strtolower($name);
if(!isset($this->_e[$name]))
$this->_e[$name]=newCList;
return$this->_e[$name]->add($value);
}
elseif(is_array($this->_m))
{
foreach($this->_mas$object)
{
if($object->getEnabled()&&(property_exists($object,$name)||$object->canSetProperty($name)))
return$object->$name=$value;
}
}
if(method_exists($this,'get'.$name))
thrownewCException(Yii::t('yii','Property"{class}.{property}"isreadonly.',
array('{class}'=>get_class($this),'{property}'=>$name)));
else
thrownewCException(Yii::t('yii','Property"{class}.{property}"isnotdefined.',
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.nhooo.com/article/184203.htm
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。