[英]Kohana Routing (and Rerouting) Issue
我正在使用PHP 5.5和Kohana 3.3
我正在开发一个网站结构,该结构始终将用户的语言偏好作为uri的第一个“项目”。
例如:
mydomain.com/en/products
mydomain.com/de/store
现在,我确信某些用户会尝试并变得更聪明,并输入类似以下内容:
mydomain.com/products
很好,我只是希望将他们重新路由到
mydomain.com/en/products
使所有内容保持一致。
只要uri在URI中只有一个“目录”,我下面的代码就可以工作,例如
mydomain.com/products
mydomain.com/store
但对于uri而言,则不像向下进一步的子目录一样:
mydomain.com/products/something
mydomain.com/store/purchase/info
这是我的路线:
Route::set('home_page', '(<lang>)')
->defaults(array(
'controller' => 'Index'
));
Route::set('default', '(<lang>(/<controller>(/<action>(/<subfolder>))))')
->defaults(array(
'controller' => 'Index',
'action' => 'index'
));
这是我的父控制器中所有其他控制器继承的代码:
public function before()
{
$this->uri = $this->request->uri();
$this->lang = $this->request->param('lang');
//If user directly inputted url mydomain.com without language information, redirect them to language version of site
//TODO use cookie information to guess language preferences if possible
if(!isset($this->lang))
{
$this->redirect('en/', 302);
}
//If the first part of path does not match a language redirect to english version of uri
if(!in_array($this->lang, ContentManager::getSupportedLangs()))
{
$this->redirect('en/'.$this->uri, 302);
}
}
您可以用此路由替换给定的两条路由:
Route::set('default', '(<lang>/)(<controller>(/<action>(/<subfolder>)))',
array(
'lang' => '(en|fr|pl)'
))
->defaults(array(
'controller' => 'Index',
'action' => 'index'
));
其中字符串(en | fr | pl)是支持的语言的串联,即'('.implode('|', ContentManager::getSupportedLangs()).')'
。
如果此解决方案仍然晦涩难懂,我们很乐意为您详细解释,但希望您能反思一下您的问题出现的原因,因为您的第一条路线home_page
已与mydomain.com/products
匹配。
您的控制器的before()
函数也应进行修改。 重定向将无法正常工作,因为您最终将重定向到例如en/ru/Index
。 那么为什么不保持它简单和使用:
public function before()
{
$default_lang = 'en';
$this->lang = $this->request->param('lang', $default_lang);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.