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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?