yii中使用event dispatcher
一、安装与配置
1,原理与安装
event dispatcher主要是用来解耦,否则不要使用,因为相对而言,算是重量级的应用。
参考官方网址:
http://components.symfony-project.org/event-dispatcher/
2,在yii中的配置
在Yii的配置文件../config/main.php中引用
//预加载,即在load前载入该组件
'preload'=>array('log', 'exception_watcher', 'os_handler', 'fp_handler'),
//注册组件
'components'=>array(
......
//注册event dispatcher
'dispatcher' => array(
'class' => 'application.extensions.event_dispatcher.EventDispatcher'
),
'fp_handler' => array(
'class' => 'application.components.FailPartsHandler',
),
......
),
3,注册组件时引入的EventDispatcher.php
require_once dirname(__FILE__) . '/event-dispatcher/lib/sfEventDispatcher.php';
/**
* It's a simple wrapper for sfEventDispatcher
*
*/
class EventDispatcher extends sfEventDispatcher {
public function init() {
}
}
二、使用
1,在函数中使用
$event = new sfEvent($this, 'failParts.create', array('Oid'=>$params['Oid']));
$str = Yii::app()->dispatcher->notify($event);
return $str->getReturnValue();
2,在component/XXHandler.php文件中调用
class FailPartsHandler {
public function init() {
$dispatcher = Yii::app()->dispatcher;
$handlers = array(
'failParts.create' => 'onCreate',
'failParts.partsMans' => 'onPartsMans',
'failParts.workers' => 'onGetWorkers',
'failParts.floors' => 'onGetFloorsByIdcName',
'failParts.sendApprove' => 'onSendApprove',
'failParts.rmsPreShow' => 'onRMSPreShow',
'failParts.outConfirm' => 'onOutConfirm',
);
// event名称 回调函数
foreach($handlers as $event_name => $handle_method) {
$dispatcher->connect($event_name, array($this, $handle_method));
}
}
public function onCreate($event) {
// 1,通过$event传回参数
$outsource = $event->getSubject();
$Oid = $event['Oid'];
// 2,调用XX soap接口(非模拟)
$result = $this->getRMSClient()->getServerInfoByOid(RMSClient::buildHeader(),$Oid);
// 3,将从XX获取的数据返回调用函数
$event->setReturnValue($result);
return true;
}
......
}