【问题标题】:Codeigniter - Get current routeCodeigniter - 获取当前路线
【发布时间】:2014-09-10 17:50:45
【问题描述】:

我正在寻求帮助以了解我的 Codeigniter 应用程序经过哪条路径。

在我的 config/routes.php 应用程序文件夹中,我得到了一些数据库生成的路由,如下所示:

$route["user/:any"] = "user/profile/$1";
$route["administration/:any"] = "admin/module/$1";


例如,如果我去 domain.net/user/MYUSERNAME,那么我想知道我是否通过了“user/:any”路线。
有没有可能知道它走哪条路线?

【问题讨论】:

  • 我认为这很难做到,也许您想获取类或知道正在使用的方法? $this->router->fetch_class();$this->router->fetch_method();。或者您可以使用简单的$this->uri->segment(n); 按功能(由您创建)构建您的路线

标签: php codeigniter


【解决方案1】:

了解路线的一种方法是:

$this->uri->segment(1);

这将为您提供此网址的 'user'

domain.net/user/MYUSERNAME

通过这种方式,您可以轻松识别您所经过的路线。

【讨论】:

  • 通缉用户/:任何。此解决方案无济于事。
【解决方案2】:

我使用@Ochi 的答案提出了这个问题。

$routes = array_reverse($this->router->routes); // All routes as specified in config/routes.php, reserved because Codeigniter matched route from last element in array to first.
foreach ($routes as $key => $val) {
$route = $key; // Current route being checked.

    // Convert wildcards to RegEx
    $key = str_replace(array(':any', ':num'), array('[^/]+', '[0-9]+'), $key);

    // Does the RegEx match?
    if (preg_match('#^'.$key.'$#', $this->uri->uri_string(), $matches)) break;
}

if ( ! $route) $route = $routes['default_route']; // If the route is blank, it can only be mathcing the default route.

echo $route; // We found our route

【讨论】:

    【解决方案3】:

    查看最新版本,如果不使用自定义路由器作为 ROUTEKEY is used and overwritten 尝试解析路由,这是不可能的

    如果您想创建和使用自定义类,只需将原始 $key 保存到另一个变量并将其设置为类属性以供以后在匹配时使用(“返回”之前的第 414 行 - 您稍后可以获取该密钥,例如 $this->fetch_current_route_key()) - 另外要记住的是,如果原始类会更改(更新),这种代码修改很容易被破坏,所以请记住这一点

    【讨论】:

    • 我制作了一个脚本,您的回答帮助我完成了。我将当前 URI 与所有路由匹配。
    猜你喜欢
    • 2014-02-25
    • 2015-12-04
    • 1970-01-01
    • 2015-09-14
    • 2015-10-08
    • 2017-07-21
    • 2016-09-26
    • 2016-04-08
    • 2019-07-15
    相关资源
    最近更新 更多