CodeIgniter:如何获取Controller,Action,URL信息

时间:2010-01-14 04:03:24

标签: codeigniter codeigniter-2

我有这些网址:

如何从这些网址获取控制器名称,操作名称。我是CodeIgniter的新手。是否有任何帮助函数来获取此信息

例如:

$params = helper_function( current_url() )

$params变成类似

的地方
array (
  'controller' => 'system/settings', 
  'action' => 'edit', 
  '...'=>'...'
)

11 个答案:

答案 0 :(得分:202)

您可以使用URI Class

$this->uri->segment(n); // n=1 for controller, n=2 for method, etc

我也被告知以下工作,但我目前无法测试:

$this->router->fetch_class();
$this->router->fetch_method();

答案 1 :(得分:129)

您应该这样做,而不是使用URI段:

$this->router->fetch_class(); // class = controller
$this->router->fetch_method();

通过这种方式,即使您位于路由URL,子域等后面,您也知道自己始终使用正确的值。

答案 2 :(得分:26)

不推荐使用这些方法。

$this->router->fetch_class();
$this->router->fetch_method();

您可以改为访问属性。

$this->router->class;
$this->router->method;

请参阅codeigniter user guide

  

URI路由方法fetch_directory(),fetch_class(),fetch_method()

     

使用属性CI_Router::$directoryCI_Router::$class和   CI_Router::$method是公开的,fetch_*()没有   更长时间做其他任何事情只返回属性 - 它没有   保持他们是有意义的。

     

这些都是内部的,未记录的方法,但我们选择了   暂时弃用它们以保持向后兼容性   以防万一。如果你们中的一些人已经使用过它们,那么现在就可以了   改为访问属性:

$this->router->directory;
$this->router->class;
$this->router->method;

答案 3 :(得分:12)

另一种方式

$this->router->class

答案 4 :(得分:10)

作为补充

$this -> router -> fetch_module(); //Module Name if you are using HMVC Component

答案 5 :(得分:5)

<强>更新

答案是在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段

答案 6 :(得分:3)

如果你使用$ this-&gt; uri-&gt;段,如果网址重写规则发生变化,则网段名称匹配将会丢失。

答案 7 :(得分:3)

在课堂或图书馆的任何地方使用本规范

    $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

答案 8 :(得分:0)

URL的最后一部分将始终是操作。请这样:

 for row, form in enumerate(self.qTable):
        col = 0
        self.tableWidget.setRowCount(row+1)
        for c in columns:
            for k,v in vars(form).items():
                if k == c:
                    self.tableWidget.setItem(row, col, QTableWidgetItem(str(v)))
                    col +=1

答案 9 :(得分:-1)

$this->router->fetch_class(); 

// fecth类控制器中的类     $这 - &GT;路由器 - &GT; fetch_method();

//方法

答案 10 :(得分:-4)

控制器类不能正常工作。

所以我建议您使用以下脚本

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];
}