开发者

Zend Router - problem - works but not as hoped

I need an custom route for my site:

everything like: www.site.com/457485789479 sould be routed to index/index wi开发者_JAVA技巧th param ID/45.. everything else should work with zend framework defaults.

i have this route:

resources.router.routes.test.type = "Zend_Controller_Router_Route"
resources.router.routes.test.route = ":id"
resources.router.routes.test.defaults.module = "default"
resources.router.routes.test.defaults.controller = "index"
resources.router.routes.test.defaults.action = "index"
resources.router.routes.test.defaults.id = ""

But now, the "URL ViewHelper" does not work and everything goes to "/" does someone see the error and can help`?


Using a custom route like example.com/:id will override the default route. This has unintended consequences because these will no longer work example.com/:module or example.com/:controller. Here is what I did to accomplish what you are asking.

I wanted this URL for static pages:

 example.com/about 

while maintaining the default route so this still works

example.com/:module
example.com/:controller

The way I did this was using a plugin to test if my request could be dispatched. If the request could not be dispatched using the default route, then I would change the request to the proper module to load my page. Here is a plugin you can modify for your needs:

class My_Controller_Plugin_StaticPageRoute extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $dispatcher = Zend_Controller_Front::getInstance()->getDispatcher();
        // Can this request be dispatched
        if (!$dispatcher->isDispatchable($request)) {
            // return if not a single level request
            if ('default' != $request->getModuleName() 
                && 'index' != $request->getActionName()) {
                return;
            }
            // Get param to be used in new request ie. example.com/:param
            $param = $request->getControllerName();
            // Set the request where to try next
            $request->setModuleName('default');
            $request->setControllerName('index');
            $request->setActionName('index');
            $request->setParam('id', $param);

            /** Prevents infinite loop if you made a mistake above **/
            if ($dispatcher->isDispatchable($request)) {
                $request->setDispatched(false);
            }

        }

    }
}


You should use Zend_Controller_Router_Route_Regex instead Router_Route

$router->addRoute('router-name', new Zend_Controller_Router_Route_Regex(
            '(\d{2,})',
            array(
                'controller' => 'index',
                'action' => 'index'
            ),
            array(1 => 'id'),
            '%d'
        ));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜