Zend Framework自定义路由

时间:2013-09-02 09:14:02

标签: php zend-framework mod-rewrite

我需要在ZF v.1.12中创建一些自定义路由:

protected function _initRouter() {
    $this->bootstrap('FrontController');
    $this->bootstrap('locale');

    $front = Zend_Controller_Front::getInstance ();
    $router = $front->getRouter ();

    $router->addRoute ( 'fastproduct', new Zend_Controller_Router_Route_Regex ( '(.+)\.html', array ('module' => 'default', 'controller' => 'products', 'action' => 'get' ), array (1 => 'q' ), '%s.html' ) );
    $router->addRoute ( 'products', new Zend_Controller_Router_Route_Regex ( 'products/(.+)\.html', array ('module' => 'default', 'controller' => 'products', 'action' => 'get' ), array (1 => 'q' ), 'products/%s.html' ) );
    $router->addRoute ( 'categories', new Zend_Controller_Router_Route_Regex ( 'categories/(.+)\.html', array ('module' => 'default', 'controller' => 'categories', 'action' => 'list' ), array (1 => 'q' ), 'categories/%s.html' ) );
    $router->addRoute ( 'cms', new Zend_Controller_Router_Route_Regex ( 'cms/(.+)\.html', array ('module' => 'default', 'controller' => 'cms', 'action' => 'page' ), array (1 => 'url' ), 'cms/%s.html' ) );
    $router->addRoute ( 'wiki', new Zend_Controller_Router_Route_Regex ( 'wiki/(.+)\.html', array ('module' => 'default', 'controller' => 'wiki', 'action' => 'help' ), array (1 => 'uri' ), 'wiki/%s.html' ) );
    $router->addRoute ( 'tlds', new Zend_Controller_Router_Route_Regex ( 'tlds/(.+)\.html', array ('module' => 'default', 'controller' => 'tlds', 'action' => 'index' ), array (1 => 'uri' ), 'tlds/%s.html' ) );

    return $router;
}

现在如果我打电话给这些链接,也可以这样做:

# http://www.mydomain.com/productname.html  
# http://www.mydomain.com/products/productname.html
# http://www.mydomain.com/categories/hosting.html
# http://www.mydomain.com/cms/mypage.html
# http://www.mydomain.com/wiki/myhelp.html
# http://www.mydomain.com/tlds/com.html
# http://www.mydomain.com/admin/

我如何将语言添加到以下所有链接中?

# http://www.mydomain.com/it/productname.html   
# http://www.mydomain.com/it/products/productname.html
# http://www.mydomain.com/it/categories/hosting.html
# http://www.mydomain.com/it/cms/mypage.html
# http://www.mydomain.com/it/wiki/myhelp.html
# http://www.mydomain.com/it/tlds/com.html
# http://www.mydomain.com/it/admin
谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您的默认路由具有可选参数,因此不需要route_4route_3route_2 - 删除它们。您仍然需要最后一个,但您没有正确使用路由链接。将其更改为:

$routeLang = new Zend_Controller_Router_Route_Regex('([a-z]{2})', array('module' => 'default', 'lang' => 'en', 'controller' => 'index', 'action' => 'index'), array (1 => 'lang' ), '%s' );
$router->addRoute('route_1', $routeLang);

您可能还想为添加的路线使用更具描述性的路线名称。

如果仍然无效,请更新您的问题以包含更新的路线配置,并提供有关如何检查匹配的路线参数的信息。