【问题标题】:Modifying url param in Kohana 3.3在 Kohana 3.3 中修改 url 参数
【发布时间】:2012-11-05 03:12:44
【问题描述】:

有没有办法在加载时更改 url 请求中的参数?

我的路由基本上检查 url http://localhost/<language>/<controller> 中的语言

但问题是,如果在语言参数中插入随机文本,它会加载默认文本,我设置翻译文件的方式将输出诸如 menu.home 之类的内容

控制器是否可以重定向到默认语言的 url? 例如http://localhost/fakeLanguage/home 将重定向到http://localhost/en/homehttp://localhost/fakeLanguage/about 重定向到http://localhost/en/about

【问题讨论】:

    标签: php kohana kohana-3


    【解决方案1】:

    您的路线必须使用正则表达式过滤段,如下所示:

    // load available language names from config
    $langs = Kohana::$config->load('lang.available');
    Route::set('lang_route', '<language>/<controller>', array('language' => '('.implode('|', $langs).')'))
        ->defaults(...);
    

    或者使用route filters,可以很方便的修改路段值。

    【讨论】:

    • 这正是我想要的,谢谢!我唯一的问题是 '['.implode('|', $langs).']' 必须是 '('.implode('|', $langs).')'
    【解决方案2】:

    虽然这只是一种可能解决方案的粗略想法,但您可能需要考虑定义一个包含所有受支持语言的数组。像这样的:

    <?php
    /*
        Part 1 - Create an array of all the known languages. Consider making this part of the application configuration file.
    */
    $languages = array(
        "en",
        "ge",
        "pirate"
    );
    ?>
    

    然后检查控制器文件中的那个数组。也许使用控制器的 before 方法:

    <?php
    /*
        Part 2 - In the controller file add a before method that checks to see if the requested language exists.
    */
    public function before(){
        if(!in_array($this->request->param('langauge'),$languages)):
            // If the language is unknown perform a redirect.
            url::redirect('DEFAULT_LANGUAGE_URL');
        endif;
    }
    ?>
    

    转换上面的 URL 结构的第一段可以使用如下代码来完成:

    <?php
        // Get the current URI
        $url = $this->request->detect_uri();
    
        // Get the query string
        // Note: If you aren't interested in preserving the query string this next line can be removed.
        if($_SERVER['QUERY_STRING'] != '') $url .= '?'.$_SERVER['QUERY_STRING'];
    
        // Set the default language. Consider setting this in your application configuration file instead.
        $defaultLanguage = 'pirate';
    
        // Replace the first URI segment with the default language.
        $redirectURL = preg_replace("/^\/.*?(\/.*)$/",("/{$defaultLanguage}$1"),$url,1);
    ?>
    

    【讨论】:

    • 我完全忘记了之前的方法。感谢您指出了这一点。这基本上就是我现在正在做的事情。谢谢你:)
    • 我仍然无法弄清楚如何只更改 uri 的一部分
    • 您的 URL 是否足够一致,可以让您遵循惯例?如果是这样,在路径上运行 RegEx 替换可能会奏效。也许有类似 "\^/.*?(/.*)$\" 的模式和 "/en$1" 的替换字符串?
    • 是的,它们足够一致,语言参数在所有路由中总是排在第一位,我会试试的,谢谢
    猜你喜欢
    • 2015-06-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多