脚本宝典收集整理的这篇文章主要介绍了zend-framework2 – ZF2如何监听特定控制器的调度事件,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Module.PHP
public function onBootstrap(EventInterface $event) { $application = $event->getApplication(); $eventManager = $application->getEventManager(); $serviceManager = $application->getServiceManager(); $eventManager->attach($serviceManager->get('MyListener')); }
MyListener.PHP
class MyListener extends AbstractListenerAggregate { public function attach(EventManagerInterface $eventManager) { $this->listeners[] = $eventManager->attach( MvcEvent::EVENT_DISPATCH,function($event) { $this->setLayout($event); },100 ); } public function setLayout(EventInterface $event) { $event->getviewmodel()->setTemplate('mylayout'); } }
这将设置所有控制器调度的布局.现在我只想在应用程序调度特定控制器时设置布局.
考虑到您要为单个特定控制器应用不同的布局,您只需执行以下操作:
<?PHP namespace MyModule\Controller; use Zend\Mvc\Controller\AbstractActionController; // Or AbstractRestfulController or your own use Zend\View\Model\viewmodel; // Or JsonModel or your own use Zend\Mvc\MvcEvent; class MyController extends AbstractActionController { public function onDispatch(MvcEvent $e) { $this -> layout('my-layout'); // The layout name has been declared somewhere in your config return parent::onDispatch($e); // Get back to the usual dispatch PRocess } // ... Your actions }
您可以为具有特殊布局的每个控制器执行此操作.对于那些不这样做的人,你不需要写任何东西.
如果您经常需要更改布局(例如,您不必处理单个控制器而是多个控制器),则可以在module.PHP中附加MvcEvent以将布局设置代码放在一个位置.
为了简单起见,我不是在这里使用自定义监听器,但您也可以使用自定义监听器.
<?PHP namespace MyModule; use Zend\Mvc\MvcEvent; class Module { public function onBootstrap(MvcEvent $e) { $eventManager = $e -> getApplication() -> getEventManager(); $eventManager -> attach( MvcEvent::EVENT_DISPATCH,// Add dispatch error event only if you want to change your layout in your error views. A few lines more are required in that case. // MvcEvent::EVENT_DISPATCH | MvcEvent::EVENT_DISPATCH_ERROR array($this,'onDispatch'),// Callback defined as onDispatch() method on $this object 100 // Note that you don't have to set this parameter if you're managing layouts only ); } public function onDispatch(MvcEvent $e) { $routeMatch = $e -> getRoutematch(); $routeParams = $routeMatch -> getParams(); swITch ($routeParams['__CONTROLLER__']) { // You may use $routeParams['controller'] if you need to check the Fully Qualified Class Name of your controller case 'MyController': $e -> getviewmodel() -> setTemplate('my-First-layout'); break; case 'OtherController': $e -> getviewmodel() -> setTemplate('my-other-layout'); break; default: // Ignore break; } } // Your other module methods... }
以上是脚本宝典为你收集整理的zend-framework2 – ZF2如何监听特定控制器的调度事件全部内容,希望文章能够帮你解决zend-framework2 – ZF2如何监听特定控制器的调度事件所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。