【问题标题】:Kohana Routing (and Rerouting) IssueKohana 路由(和重新路由)问题
【发布时间】:2013-02-05 18:43:16
【问题描述】:

我正在使用 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

但不适用于 uris,例如以下子目录:

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);
            }
          }

【问题讨论】:

    标签: php kohana kohana-3


    【解决方案1】:

    你可以用这个替换给定的两条路线:

    Route::set('default', '(<lang>/)(<controller>(/<action>(/<subfolder>)))',
    array(
        'lang' => '(en|fr|pl)'
    ))
    ->defaults(array(
        'controller' => 'Index',
        'action' => 'index'
    ));
    

    字符串 (en|fr|pl) 是您支持的语言的串联,即'('.implode('|', ContentManager::getSupportedLangs()).')'

    如果这个解决方案仍然晦涩难懂,我很乐意更详细地解释它,但我希望你能在反思中看到你的问题是因为你的 first 路由 home_page 被匹配例如mydomain.com/products.

    您的控制器的before() 函数也应该修改。重定向将无法正常工作,因为您最终将重定向到例如en/ru/Index。那么为什么不保持简单并使用:

        public function before()
        {           
            $default_lang = 'en';
            $this->lang = $this->request->param('lang', $default_lang);
        }
    

    【讨论】:

    • 当用户没有在 url 中指定语言(en、fr 或 pl)时,这不会提供 404 吗?我想获取 url /products/something 并将它们路由到 /en/products/something。我希望用户完全不知道如果他们在地址栏中输入地址,他们必须在 url 中指定一种语言
    • 不,它不会提供 404:试试吧!原因是路由中(&lt;lang&gt;/) 中的括号使该部分成为可选的。因此,如果使用支持的语言没有找到匹配项,它会将其视为不存在。
    • 你当然是对的。抱歉,我现在才开始尝试。非常感谢您的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多