use*_*728 5 zend-framework-modules zend-framework2
我想在我的模块中的每个操作之前编写一些代码来运行.我试过挂钩,onBootstrap()但代码也运行在其他模块上.
对我有什么建议吗?
有两种方法可以做到这一点.
一种方法是创建一个serice并在每个控制器调度方法中调用它
Use onDispatch method in controller.
class IndexController extends AbstractActionController {
/**
*
* @param \Zend\Mvc\MvcEvent $e
* @return type
*/
public function onDispatch(MvcEvent $e) {
//Call your service here
return parent::onDispatch($e);
}
public function indexAction() {
return new ViewModel();
}
}
Run Code Online (Sandbox Code Playgroud)
不要忘记在代码之上包含以下库
use Zend\Mvc\MvcEvent;
Run Code Online (Sandbox Code Playgroud)
第二种方法是使用发送时的事件通过Module.php执行此操作
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module {
public function onBootstrap(MvcEvent $e) {
$sharedEvents = $e->getApplication()->getEventManager()->getSharedManager();
$sharedEvents->attach(__NAMESPACE__, 'dispatch', array($this, 'addViewVariables'), 201);
}
public function addViewVariables(Event $e) {
//your code goes here
}
// rest of the Module methods goes here...
//...
//...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3999 次 |
| 最近记录: |