项目使用的是ZendFramework2 经常有访问另外Controller下Action的需求,常见的方法是使用CURL
先上代码
publicfunction onDispatch(MvcEvent$e)
{
//可在此获取dispatch params 如 $this->params('action')
return parent::onDispatch($e); // TODO: Change the autogenerated stub
}
public function DispatchAction() {
try {
//开启事务
$this->getDbAdapter()->getDriver()->getConnection()->beginTransaction();
//同时可在此为请求设置参数 相当于$_POST
$request = $this->getRequest();
$request->getPost()->set('msg', 'test');
//Test\Controller\Index 为路由controller名 array里面参数如访问的action名等其他自定义参数
$var = $this->forward()->dispatch('Test\Controller\Index', array(
'action' => 'CallBack',
'controller'=>'22'
));
//提交事务
$this->getDbAdapter()->getDriver()->getConnection()->commit();
return $var;
} catch (\Exception $e) {
return new JsonModel(array('result'=>false,'msg'=>$e->getMessage()));
}
}
//dispatch调用的方法
public function CallBackAction() {
try {
//判断是否已经开启了事务操作
if(!$this->getDbAdapter()->getDriver()->getConnection()->inTransaction()){
$this->getDbAdapter()->getDriver()->getConnection()->beginTransaction();
}
$request = $this->getRequest();
//初始化model
$userModel = new UserModel($this->getDbadapter());
$sql = "delete from user_list";
//调用封装好的数据库操作方法 执行SQL语句
$ret = $userModel->exec($sql);
return new JsonModel(array('result'=>true,'msg'=>$_POST,'data'=>$request->getPost('msg')));
} catch (\Exception $e) {
return new JsonModel(array('result'=>false,'msg'=>$e->getMessage()));
}
相比于传统CURL的优点
- 保持了两边事务的一致性
- 调试代码更为明了,可控