Codeigniter -获取当前路由

5ssjco0h  于 2023-01-22  发布在  其他
关注(0)|答案(4)|浏览(176)

我正在寻求帮助,以了解我的Codeigniter应用程序通过哪条路线。
在我的应用程序文件夹中的config/routes.php我得到了一些数据库生成的路线,可以看起来像这样:

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

如果我例如去domain.net/user/MYUSERNAME,那么我想知道我得到通过的路线“用户/:任何”.
有可能知道它走哪条路吗?

6xfqseft

6xfqseft1#

了解路线的一种方法是使用以下命令:
$this->uri->segment(1);
这将为您提供此URL的**“用户”**:

域名.net/用户/我的用户名

通过这种方式,你可以很容易地确定你所经过的路线。

ldioqlga

ldioqlga2#

我用@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
to94eoyn

to94eoyn3#

查看最新版本,不使用定制路由器是不可能的,因为ROUTEKEY被使用并被覆盖,试图解析路由
如果您希望创建和使用定制类,只需将原始$key保存到另一个变量中,并将其设置为类属性,以便以后在匹配时使用(“return”之前的第414行-您可以稍后获取该键,例如$this->fetch_current_route_key())-需要记住的另一件事是,如果原始类发生变化,这种代码修改很容易中断(更新)所以请记住这一点

kuarbcqp

kuarbcqp4#

对于代码点火器4:

var_dump(service('router')->getMatchedRoute());

它将返回如下内容:

[
    "{locale}/(.*)",
    "\App\Controllers\Home_controller::any/home"
];

相关问题