如何在CodeIgniter钩子中检索第三个URI段

5

我正在编写自定义的post_controller hook。正如我们所知,CodeIgniter的URI结构如下:

example.com/class/function/id/

我的代码如下:

function hook_acl()
{
    global $RTR;
    global $CI;

    $controller = $RTR->class; // the class part in uri
    $method = $RTR->method; // the function part in uri
    $id = ? // how to parse this?

    // other codes omitted for brevity
}

我已经浏览了核心的Router.php文件,这让我感到困惑。
谢谢。
2个回答

8

使用CodeIgniter URI核心类

通常在CodeIgniter的Hooks中,我们需要加载/实例化URI核心类才能访问方法。

  • 对于post_controller_constructorpost_controller等钩子,我们可以获取CodeIgniter超级对象并使用uri类:
# Get the CI instance
$CI =& get_instance();

# Get the third segment
$CI->uri->segment(3);
  • 但是对于pre_controller钩子,我们无法访问CodeIgniter的超级对象,所以我们必须手动加载URI核心类,如下所示:
# Load the URI core class
$uri =& load_class('URI', 'core');

# Get the third segment
$id = $uri->segment(3); // returns the id

使用纯PHP

在这种方法中,您可以使用$_SERVER数组来获取URI段,如下所示:

$segments = explode('/', trim($_SERVER['REQUEST_URI'], '/'));

$controller = $segments[1];
$method     = $segments[2];
$id         = $segments[3];

1
您可以使用router类:
$this->router->fetch_class();
$this->router->fetch_method();

或者使用URI类:

$this->uri->segment(1); // the class
$this->uri->segment(2); // the function
$this->uri->segment(3); // the ID

1
谢谢,它有效。 (使用$CI->uri->segment(3);)。 Codeigniter已经有一个可供使用的类。 我应该更仔细地阅读CI用户指南。 - Darren20

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接