这里的第一个问题是,在使用路由时,您需要有非常具体的约束才能将规则与这么多变量匹配。
我建议不要同时接受 //url/:lang/:module/:controller/:action 和 //url/:module/:controller/:action 而是只使用第一个结构。这样可以更容易地将第一个规则与 //url/:lang/:controller/:action 隔离开来,每个规则只有 2 个规则,每个规则都有不同的“单词”(URL 部分)。
$withModule = new Zend_Controller_Router_Route(
':lang/:module/:controller/:action',
array()
);
$withoutModule = new Zend_Controller_Router_Route(
':lang/:controller/:action',
array(
'module' => 'default'
)
);
$router->addRoute('withModule', $withModule);
$router->addRoute('withoutModule', $withoutModule);
在第一个路由中,您没有指定任何默认值,因此它与用于第二个路由的 URL 不匹配,而在第二个路由中,您默认模块(因为 ZF 需要该信息)。
至于第三条规则,我建议使用基本祖先控制器,例如 MyLib_Controller 并在其 init() 方法中验证是否收到了语言参数,如下例所示:
if(!$this->_getParam('lang')) {
//this should cover the 3rd use case
$this->_redirect('/en/' + $this->view->url(), array('exit' => true, 'prependBase' => false));
} else {
//setup Zend_Translate
}
另一种可能性是将 :lang 变量限制为只有 2 个字母的单词,但这会产生问题,我更愿意避免它。