php - 小花 3.2。 - 如何在 URI 中使用连字符

标签 php kohana uri kohana-3 routes

最近我一直在研究 SEO 以及使用连字符或下划线的 URI 如何被区别对待,尤其是 Google 将连字符视为分隔符。

无论如何,急于调整我当前的项目以满足此标准,我发现因为 Kohana 使用函数名称来定义页面,所以我收到了意外的“-”警告。​​

我想知道是否有任何方法可以在 Kohana 中使用 URI,例如:

http://www.mysite.com/controller/function-name

显然我可以为此设置一个 routeHandler...但是如果我要让用户生成内容,即新闻。然后我必须从数据库中获取所有文章,生成 URI,然后为每篇文章进行路由。

是否有任何替代解决方案?

最佳答案

注意:这与 Laurent's answer 中的方法相同,只是稍微更面向对象。 Kohana 允许人们非常容易地重载任何系统类,因此我们可以使用它来节省我们的一些打字时间,并允许将来进行更清晰的更新。

我们可以在 Kohana 中插入请求流,并修复 URL 操作部分中的破折号。为此,我们将覆盖 Request_Client_Internal 系统类及其 execute_request() 方法。在那里我们将检查 request->action 是否有破折号,如果是的话我们会将它们切换为下划线以允许 php 正确调用我们的方法。

第 1 步打开您的application/bootstrap.php 并添加以下行:

define('URL_WITH_DASHES_ONLY', TRUE);

如果您需要在 url 中使用下划线,您可以使用此常量在某些请求中快速禁用此功能。

第 2 步在以下位置创建一个新的 php 文件:application/classes/request/client/internal.php 并粘贴此代码:

<?php defined('SYSPATH') or die('No direct script access.');

class Request_Client_Internal extends Kohana_Request_Client_Internal {

    /**
     * We override this method to allow for dashes in the action part of the url
     * (See Kohana_Request_Client_Internal::execute_request() for the details)
     *
     * @param   Request $request
     * @return  Response
     */
    public function execute_request(Request $request)
    {
        // Check the setting for dashes (the one set in bootstrap.php)
        if (defined('URL_WITH_DASHES_ONLY') and URL_WITH_DASHES_ONLY == TRUE) 
        {
            // Block URLs with underscore in the action to avoid duplicated content
            if (strpos($request->action(), '_') !== false)
            {
                throw new HTTP_Exception_404('The requested URL :uri was not found on this server.', array(':uri' => $request->uri()));
            }

            // Modify action part of the request: transform all dashes to underscores
            $request->action( strtr($request->action(), '-', '_') );
        }
        // We are done, let the parent method do the heavy lifting
        return parent::execute_request($request);
    }

} // end_class Request_Client_Internal

它所做的只是用下划线替换 $request->action 中的所有破折号,因此如果 url 是 /something/foo-bar,Kohana 现在会很乐意将它路由到我们的 action_foo_bar( ) 方法。

同时我们用下划线屏蔽了所有的 Action ,避免了重复内容的问题。

关于php - 小花 3.2。 - 如何在 URI 中使用连字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7404646/

相关文章:

javascript - 如何拆分通过 json_encode 传递的 mysql 数据库中的行以显示在单独的文本框中

javascript - Searchfuntion 在 Symfony2 中使用 ajax 调用

php - kohana orm 顶级用户

nginx - kohana 和 nginx/php-fpm 的问题

Android 默认音调选择器问题(带有通知和警报的默认音调)

php - 阻止通过 http 直接访问文件,但允许 php 脚本访问

php - 如何获得标记列表的第二个最大值?

php - 使用 Kohana 的数据库库绑定(bind)参数

javascript - 如何使用纯 JavaScript 解析来自 API 的 JSON?

c# - 如何从 C# 中的 Uri 中提取文件名?