代码点火器:如何获取Controller、Action、URL信息
-
20-09-2019 - |
题
我有这些网址:
如何从这些 URL 中获取控制器名称、操作名称。我是 CodeIgniter 新手。是否有任何辅助函数可以获取此信息
前任:
$params = helper_function( current_url() )
在哪里 $params
变成类似的东西
array (
'controller' => 'system/settings',
'action' => 'edit',
'...'=>'...'
)
解决方案
你可以使用 URI 类:
$this->uri->segment(n); // n=1 for controller, n=2 for method, etc
我还被告知以下工作有效,但目前无法测试:
$this->router->fetch_class();
$this->router->fetch_method();
其他提示
您应该这样做,而不是使用 URI 段:
$this->router->fetch_class(); // class = controller
$this->router->fetch_method();
这样,即使您位于路由 URL 后面、子域中等,您也知道您始终使用正确的值。
这些方法已被弃用。
$this->router->fetch_class();
$this->router->fetch_method();
您可以改为访问属性。
$this->router->class;
$this->router->method;
URI 路由方法 fetch_directory()、fetch_class()、fetch_method()
具有属性
CI_Router::$directory
,CI_Router::$class
和CI_Router::$method
公开及其各自的fetch_*()
不再采取其他任何操作来返回属性 - 保留它们是没有意义的。这些都是内部的,无证件的方法,但是我们现在选择将它们贬低,以便以防万一,以保持向后兼容。如果你们中的一些人使用了它们,那么您现在可以访问属性:
$this->router->directory; $this->router->class; $this->router->method;
其他方式
$this->router->class
作为补充
$this -> router -> fetch_module(); //Module Name if you are using HMVC Component
更新
答案是在 2015 年添加的,现在不推荐使用以下方法
$this->router->fetch_class(); in favour of $this->router->class;
$this->router->fetch_method(); in favour of $this->router->method;
您好,您应该使用以下方法
$this->router->fetch_class(); // class = controller
$this->router->fetch_method(); // action
为此目的,但要使用它,您需要从 CI_Controller
它的作用就像一个魅力,你不应该使用 uri 段
如果您使用 $this->uri->segment ,如果 url 重写规则发生变化,段名称匹配将会丢失。
在类或库中的任何位置使用此代码
$current_url =& get_instance(); // get a reference to CodeIgniter
$current_url->router->fetch_class(); // for Class name or controller
$current_url->router->fetch_method(); // for method name
URL 的最后一段始终是操作。请像这样:
$this->uri->segment('last_segment');
$this->router->fetch_class();
// FECTH类controller $ this-> router-> fetch_method()中的类;
// 方法
控制器类没有任何功能。
所以我建议您使用以下脚本
global $argv;
if(is_array($argv)){
$action = $argv[1];
$method = $argv[2];
}else{
$request_uri = $_SERVER['REQUEST_URI'];
$pattern = "/.*?\/index\.php\/(.*?)\/(.*?)$/";
preg_match($pattern, $request_uri, $params);
$action = $params[1];
$method = $params[2];
}
不隶属于 StackOverflow