本文實(shí)例講述了Yii Framework框架中的事件event原理與應(yīng)用。分享給大家供大家參考,具體如下:
再談Yii Framework中的事件event,我寫過的關(guān)于Yii事件event的另一篇文章
Yii Framework 中事件和行為的區(qū)別和應(yīng)用 https://www.jb51.net/article/184208.htm
假設(shè)有類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 來直接設(shè)置事件的。
綁定到全局事件處理
方法一:
直接在main.php里面定義
/***************************************************
在我們想要的內(nèi)容的前后出現(xiàn)了這些代碼
只是為了說明,我們添加的內(nèi)容是要放在
這個(gè)配置數(shù)據(jù)的一維里面。
'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'));
綁定到局部事件處理
隨時(shí)隨地?zé)o論在controller還是model里面,只要是CComponent的子類,都可以這樣定義,
$myComponent->onClick = $callback;
這里的 $callback 指向了一個(gè)有效的 PHP 回調(diào)。它可以是一個(gè)全局函數(shù)也可以是類中的一個(gè)方法。
如果是后者,它必須以一個(gè)數(shù)組的方式提供 : array($object,'methodName')
。
其它文章推薦:
Yii組件的事件機(jī)制分析 https://www.jb51.net/article/184203.htm
更多關(guān)于Yii相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結(jié)》、《php優(yōu)秀開發(fā)框架總結(jié)》、《smarty模板入門基礎(chǔ)教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- 從零開始學(xué)YII2框架(六)高級(jí)應(yīng)用程序模板
- yii2高級(jí)應(yīng)用之自定義組件實(shí)現(xiàn)全局使用圖片上傳功能的方法
- YII Framework框架使用YIIC快速創(chuàng)建YII應(yīng)用之migrate用法實(shí)例詳解
- YII Framework框架教程之使用YIIC快速創(chuàng)建YII應(yīng)用詳解
- Yii2框架redis基本應(yīng)用示例
- Yii框架學(xué)習(xí)筆記之應(yīng)用組件操作示例
- Yii框架常見緩存應(yīng)用實(shí)例小結(jié)
- Yii Framework框架中事件和行為的區(qū)別及應(yīng)用實(shí)例分析
- Yii框架應(yīng)用組件用法實(shí)例分析
- Yii 框架應(yīng)用(Applications)操作實(shí)例詳解