dongsuiying7773 2014-10-21 13:17
浏览 26
已采纳

ZF2控制器动作执行公共代码

Apologies if this is a basic question but I have attempted to find an answer in the ZF2 documentation and I can't find a clear answer.

I have a set of Controllers each containing a set of actions. I would like each action to check for a certain parameter being present in the request. What is the best to ensure that this gets done for all actions such that if I add a new action it will automatically be catered for too?

Many thanks for your help.

  • 写回答

1条回答 默认 最新

  • duanshan3065 2014-10-21 15:44
    关注

    You could extend the AbstractActionController and add your custom methods or override existing ones to your needs.

    use Zend\Mvc\Controller\AbstractActionController;
    
    abstract class AbstractCustomController extends AbstractActionController
    {
       //custom methods
    }
    

    once That is done you then simply access your custom controller trough namespaces and extend it with the new controllers.

    <?php
    
    namespace Custom\Controller; 
    
    use Zend\View\Model\ViewModel;    
    use Custom\Controller\AbstractCustomController;
    
    class NewController extends AbstractUserController {
       //new controller which has access to methods from extented AbstractController
    }
    

    You didnt specify on what exactly you are checking on. But using a MVC Event might be cleaner and easier to implement. You'll simply add some functionality to your module.php for example:

    public function onBootstrap(MvcEvent $e) {
    //check request
    }
    

    This is just an example and may not work though. Depending on the Order of events the request may not be filled at this given point and you'd be forced to use another one.

    I once used the onDispatch(\Zend\Mvc\MvcEvent $e) provided by the AbstractActionController for a task that was a little bit similar to yours. But then again if you could be more specific we'd probably could give you a more specific answer.

    best regards and good luck!

    Edit: Regarding your question in the comment you could listen to the routing event and get your params there.

    //Module.php within your onBootstrap Method
    $application = $e->getApplication();
    $eventManager = $application->getEventManager();
    $eventManager->attach('route', function(MvcEvent $mvcEvent) {
       $params = $mvcEvent->getRouteMatch()->getParams();
       echo '<pre>'; print_r($params); exit;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算