Untitled-1

Dynamic routing from database in Codeigniter

This is a common question I’ve came across whilst helping out around the Codeigniter forums. There are an array of solutions for this but in this post, I am going to detail how I create my routes. I’m not claiming this is the best solution but it’s a solution I like and I’m sticking with it, alright?

Create Routes from Database in Codeigniter

My problem first occurred when I was creating a CMS and I wanted to allow users to add pages which also included specifying there own URL. The new page would then be accessed via http://domain.com/my-new-page. This isn’t really a problem if you would be happy with a URL such as: http://domain.com/pages/5, however, nowadays for SEO and cleanliness, it’s best to avoid that kind of structure.

My Solution

NOTE: This example demonstrates me using this for PAGES but it can be applied to anything really with a few changes.

I ended up at this solution after looking through various suggestions on the Codeigniter forum. In summary, every time I create or edit a page, I write out a PHP array to a file and this file is then included in my application/config/routes.php file. This supports parent/child relationships which can give me hierarchical urls such as http://domain.com/parent/child/grandchild/greatgrandchild.

Example Routes:

What we will end up with is a separate file which contains a route for every page in our database which will look like this:

$route["home"] = "pages/display/1";
$route["about"] = "pages/display/2";
$route["about/the-company"] = "pages/display/3";

Writing routes from our database

I chose to write my routes to application/cache/routes.php , but you can store the file wherever you want.

I have the following functions in an admin controller which allows users to edit/create new pages, however, you can move them to an external library or helper or wherever you like really. Just remember if you are going to move them out to a library, you will need to get an instance of the CI super object using;

$CI =& get_instance();

I have commented the functions where I feel necessary – they are quite simple really.

    public function save_routes()
    {
        // this simply returns all the pages from my database
        $routes = $this->pages_model->get_all();

        // write out the PHP array to the file with help from the file helper
        if ( !empty( $routes ) )
        {
            // for every page in the database, get the route using the recursive function - _get_route()
            foreach( $routes as $route )
            {
                $data[] = '$route["' . $this->_get_route($route['id']) . '"] = "' . "pages/display/{$route['id']}" . '";';
            }

            $output = implode("\n", $data);

            $this->load->helper('file');
            write_file(APPPATH . "cache/routes.php", $output);
        }
    }

    // Credit to http://acairns.co.uk for this simple function he shared with me
    // this will return our route based on the 'url' field of the database
    // it will also check for parent pages for hierarchical urls
    private function _get_route($id)
    {
        // get the page from the db using it's id
        $page = $this->pages_model->get_page($id);

        // if this page has a parent, prefix it with the URL of the parent -- RECURSIVE
        if($page["parent_id"] != 0)
                $prefix = $this->_get_route($page["parent_id"])."/".$page['url'];
        else
                $prefix = $page['url'];

        return $prefix;
    }

Things to note:

  • Your database field names for id, parent_id, url might be different – please change these as required
  • The routed URL pages/display/{$id} is my method for displaying pages, remember and change this as you see fit
  • As I am working with pages, I have the code in there to cycle back through parent pages – you may not need this

Including database routes

This is the easy part, at the end of application/config/routes.php, simply add in:

include_once APPPATH . "cache/routes.php";

Remember APPPATH simply returns the directory of the Codeigniter Application and you should change this path if you saved your database routes somewhere else.

Keeping the routes updated

All we need to do now is rewrite the applications/cache/routes.php file everytime we update or create a page. For example:

public function add_page()
{
 // all your code for adding a page to your database here
$this->save_routes();
}

public function edit_page()
{
 // all your code for editting an existing page here
$this->save_routes();
}

This assumes your save_routes method is inside the same controller as your add/edit functions.

Hopefully this will have you generating your dynamic routes from a database using Codeigniter, if you need assistance, feel free to leave a comment or head over to the Codeigniter Forums for support.

This entry was posted in Uncategorized. Bookmark the permalink.

10 Responses to Dynamic routing from database in Codeigniter

  1. this is very help me. so basically I know how to solve my dynamic page now. thank you.

  2. Thanks for your thoughts and examples. I am trying to write a super simple cms with categories and this is an interesting solution I will for sure tune to my needs.

  3. Great Solution!
    Thank very much!

  4. Thanks for the article. I have developed my own way, which I guess, is simplier:

    1) I have a functions_helper which is loaded with the autoload
    2) and a config/routes_dynamic.php file

    in a helper I wrote a function:

    /**
    * Get dynamic routing for static pages
    */
    function fillDynamicRouting()
    {
    $ci = &get_instance();
    $ci->load->model(‘System/PagesModel’, ‘pages’);

    $data = array();
    $pages = $ci->pages->listing(array(), 0, 0, array(‘listingTreshold’ => FALSE));

    foreach($pages['recordset'] as $page) {
    $data[] = ‘\t\t$route["'.$page['pageRoute'].’”] = “‘ . “pages/view/{$page['pageId']}” . ‘”;’;
    }
    $output = “”;
    file_put_contents(APPPATH . “config/routes_dynamic.php”, $output);
    }

    and than I include the config/routes_dynamic.php file in the config/routing.php with an include.

    Thats all. Hope you’ll find it helpfull. If you have any question or need any other code examples to publish – let me know.

  5. Thanks for the tip :D

    My code is simple:

    public function save_routes()
    {
    // this simply returns all the pages from my database
    $routes = $this->entradas_model->all();

    // write out the PHP array to the file with help from the file helper
    if ( !empty( $routes ) )
    {
    $data[] = 'titulo) . '"] = "main/entrada/' . $route->id . '";';
    //$data[] = '$route["' . $this->_get_route($route['id']) . '"] = "' . "pages/display/{$route['id']}" . '";';
    }

    $output = implode("\n", $data);

    $this->load->helper('file');
    write_file(APPPATH . "cache/routes.php", $output);
    echo "Done.";
    }
    }

  6. nice post man. two thumb for you :)

  7. Hello, I was getting problem to know fully about route.php. Now this article give important information which i want to know.

    THANK U VERY MUCH

  8. I like the helpful information you provide in your articles. Ill bookmark your blog and check again here regularly. I’m quite sure Ill learn lots of new stuff right here! Best of luck for the next!

  9. Awesome explanation. Exactly what I was looking for! Thanks man.

  10. Keep posting stuff like this i really like it

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

RSS Feed Follow me on Twitter! Connect with me on Linked In! Add me on Skype!

LATEST FROM THE BLOG