Extending the CodeIgniter URI class to simplify pagination base_url option

In a lot of my controllers, I use pagination along with the HTML <base> tag’s href attribute for relative link URLs.

Example URL: http://www.domain.com/admin/users/index/pagination_offset

HTML Base tag: <base href=”http://www.domain.com/admin/”>

What this means, is I usually have to build pagination’s base_url option based on where I am and what information is being passed in the URI. A lot of times it ends up looking something like…

$this->load->library('pagination', array(
    'base_url'       => $this->uri->segment(2) . '/' . $this->uri->segment(3) . '/' . $this->uri->segment(4),
    'total_rows'     => $total_rows,
    'per_page'       => 20,
    'uri_segment'    => 4
));

What I decided to do what extend the core CodeIgniter URI class to provide a basic slice method to grab a chunk of the URI by applying PHP’s array_slice function to the segments property of the URI class.

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_URI extends CI_URI {

    public function __construct()
    {
        parent::__construct();
    }

    public function segments_slice($offset = 0, $length = NULL)
    {
        if ($offset == 0 && $length === NULL) return $this->uri_string;
        return implode('/', array_slice($this->segments, (int) $offset, $length));
    }

}

/* End of file MY_URI.php */
/* Location: ./application/core/MY_URI.php */

Now instead of the first example, I call the following method.

$this->load->library('pagination', array(
    'base_url'       => $this->uri->segments_slice(1, 3),
    'total_rows'     => $total_rows,
    'per_page'       => 20,
    'uri_segment'    => 5
));

Considering the low number of calls made to the URI library, I doubt it has any noticeable performance improvements, but I think it provides nicer code and is pretty easy to elicit what is happening just by seeing the name of the method 😉

Leave a Reply

Your email address will not be published. Required fields are marked *