Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the third uri segment in a codeigniter hook

I'm writing a custom post_controller hook. As we know, codeigniter uri structure is like this:

example.com/class/function/id/

and my code:

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
}

I've browsed the core Router.php file, which puzzled me a lot.

thanks.

like image 722
Darren20 Avatar asked Mar 10 '14 12:03

Darren20


2 Answers

Using CodeIgniter URI core class

Generally within CodeIgniter Hooks, we need to load/instantiate the URI core class to reach the methods.

  • For post_controller_constructor, post_controller, ... hooks, we can get the CodeIgniter super object and use use the uri class:
# Get the CI instance
$CI =& get_instance();

# Get the third segment
$CI->uri->segment(3);
  • But for pre_controller hook, we don't have access to CodeIgniter super object So we have to load the URI core class manually as follows:
# Load the URI core class
$uri =& load_class('URI', 'core');

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

Using pure PHP

In this approach you can use $_SERVER array to fetch the URI segments as:

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

$controller = $segments[1];
$method     = $segments[2];
$id         = $segments[3];
like image 72
Hashem Qolami Avatar answered Nov 17 '22 17:11

Hashem Qolami


You can use the router class :

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

Or the URI class :

$this->uri->segment(1); // the class
$this->uri->segment(2); // the function
$this->uri->segment(3); // the ID
like image 38
ncrocfer Avatar answered Nov 17 '22 16:11

ncrocfer