dongmen9517 2013-05-30 08:46
浏览 22
已采纳

ZF2自定义路由

I am trying to setup routing for our ZF2 application.

We have URLS like this:

/foo/bar.json            >>> should call /Controller/Foo/BarController.php
/foo/bar/123.json        >>> should call /Controller/Foo/BarController.php
/foo/baz/bar.json        >>> should call /Controller/FooController.php

and the underlaying controller structure

/Controller/Foo/BarController.php
/Controller/FooController.php

It should route by looking up in the directory structure. So /foo/baz/bar.json should look if /Controller/Foo/Baz/BarController.php exists. If not, look if /Controller/Foo/BazController.php exists, else look for /Controller/FooController.php and else give a 404

However i do not seem to get mutch useful information from the zend documentation. I looked at the existing routers but it does not seem to me that any of these match the required functionality.

Also there does not seem to be any information in the zend docs about creating a custom router.

I tried to extend the Literal router and create one of my own by overriding the match() function and returning the RouteMatch object if a match was found, but it still gives me a 404 with a notice that thee was no matched route.

The module.config file was ofcourse also edited to add the new router. and added it to the invokables

Can anyone tell me some starters about how to write a custom router or does anyone know any good information about doing this?

  • 写回答

2条回答 默认 最新

  • dongyi7901 2013-05-30 09:36
    关注

    Not sure if it is the best way.

    You can point all your URLS to one controller e.g. /Controller/RouteController.php. And there you can traverse the url and dispath the appropriate controller:

    public function indexAction()
    {
        $event = $this->getEvent();
        $routeMatch = $event->getRouteMatch();
    
        $locator = $this->getServiceLocator();
        if ($locator->has('ControllerLoader')) {
            $locator = $locator->get('ControllerLoader');
        }
    
        $url = parse_url($this->getRequest()->getUri());
        $path = str_replace('.json', '', $url['path']);
        $path = explode('/', trim($path, '/'));
    
        while (sizeof($path)){
            $controllerName = 'Controller\\' .implode('\\', $path);
            if ($locator->has($controllerName)) {
                return $this->forward()->dispatch($controllerName, $routeMatch->getParams());
            }
    
            array_pop($path);
        }
    
        //not found
    }
    

    Be sure to define your controllers in module config:

    array(
      'controllers' => array(
        'invokables' => array(
            'Controller\Foo\Baz' => 'Controller\Foo\BazController',
            ...
        )
      ),
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?