简体   繁体   中英

Zend Framework - How to loop through routes in a controller

I'm in a controller in Zend and I want to loop through the current routes. I am able to get the routes, but they are protected so I can't loop through them. Here is what I am using to get the routes:

    $routes = Zend_Controller_Front::getInstance()->getRouter();

    foreach ($routes as $key => $route) {
         // I need to get controller and action for each $route but it is protected, see debug output of $route below to see what I am trying to access.
    }

I see the _routes and get the name of it but I need the controller and action for each route and those are protected. Any way to achieve this? I've scoured both Google and Stack and can't seem to find anything.

EDIT: Just to ellaborate more with the first answer given. I have no problem getting the routes, it returns an array of Zend_Controller_Router_Route_Chain objects which I can loop through and looks something like so:

    object(Zend_Controller_Router_Route_Chain)#83 (5) {
              ["_routes":protected]=>
           array(2) {
                [0]=>
                object(Zend_Controller_Router_Route_Hostname)#34 (13) {
                  ["_hostVariable":protected]=>
                  string(1) ":"
                  ...
                }
                [1]=>
                object(Zend_Controller_Router_Route_Static)#78 (4) {
                  ["_route":protected]=>
                  string(0) ""
                  ["_defaults":protected]=>
                  array(3) {
                    ["module"]=>
                    string(7) "default"
                    ["controller"]=>
                    string(5) "index"
                    ["action"]=>
                    string(14) "hubverify-home"
                  }
                  ...
                }
              }

The default router is Zend_Controller_Router_Rewrite which has a method getRoutes , thus to get all routes try: Zend_Controller_Front::getInstance()->getRouter()->getRoutes()

EDIT: since Zend_Controller_Router_Route_Chain don't have getter for the $_routes property you have two options:

A) Extend Zend_Controller_Router_Route_Chain :

class My_Controller_Router_Route_Chain extends Zend_Controller_Router_Route_Chain
{
    public function getRoutes()
    {
        return $this->_routes;
    }    
}

B) Use ReflectionProperty to set $_routes as accesable:

$prop = new ReflectionProperty(get_class($chainedRoute), '_routes');
$prop->setAccessible(true);
var_dump($prop->getValue($chainedRoute));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM