Getting $_GET parameters from route in Zend Framework 2

后端 未结 3 2120
失恋的感觉
失恋的感觉 2021-02-09 04:45

Zend Framework 1 had a very simple way of parsing URL routes and setting found params in the $_GET superglobal for easy access. Sure, you could use ->getParam($something) inside

3条回答
  •  暖寄归人
    2021-02-09 05:27

    First of all, you shouldn't use $_GET or any other superglobal directly if you're building on an object oriented stack. The SRP is invalidated this way.

    If you have no possibility to change the way of your (3rd party?) librarys to change you might want to hook into the MvcEvent, listen to --event-- and then get the RouteMatch, you may fill $_GET with a simple loop.

    For a most-performant answer, you should know if the named library will be needed for every action, just for one module, or only in certain controllers/actions. If the latest is your use-case, you should write a controller plugin instead.

    some example code for the first approach:

    namespace YourModule;
    use Zend\EventManager\EventInterface as Event;
    use Zend\Mvc\MvcEvent;
    
    class Module
    {
        ...
    
        public function onBootstrap(Event $ev)
        {
            $application = $e->getApplication();
            $eventManager = $application->getEventManager();
    
            $eventManager->attach('route', function(MvcEvent $mvcEvent) {
                $params = $mvcEvent->getRouteMatch()->getParams();
    
                foreach ( $params as $name => $value )
                {
                    if ( ! isset($_GET[$name]) 
                    {
                        $_GET[$name] = $value;
                    }
                }
            });
        }
    }
    

提交回复
热议问题