Search code examples
phpcodeignitercodeigniter-routing

Database driven routing in CodeIgniter 2.x


I am creating a site that will have a lot of routes that will need to be added to the routes file (800+) - obviously I do not want to manually add these one by one into the routes config file.

Can anyone suggest the best practice to have my routes loaded automatically from the database. Is there a suitable library/helper that will perform this task that works with version 2.x

For instance..

$route['apple'] = 'brands/index';
$route['blackberry'] = 'brands/index';
$route['htc'] = 'brands/index';
$route['samsung'] = 'brands/index';

These are just a few of the brands i'd be adding to the routes - but there are hundreds of these so i'd want to have this loaded from a database rather than manually type these in. Also - would this method have any impact on site performance having them load from the database?

I am using Codeigniter v2.1.3


Solution

  • If you were to constantly query the database (on each page load) via a DB call in the application/config/routes.php file then I imagine there would be a large impact on performance.

    What I would suggest (and the way I have done this previously) is to include the following line at the bottom of your routes.php file and save all your routes to a routes.php file in the cache folder.

    require_once APPPATH . 'cache/routes.php';
    

    You can then write all your results to the cache file (using CI's file helper) with a function similar to the below:

    public function save_routes() {
            $routes = $this->routes_model->get_all_routes();
    
            $data = array();
    
            if (!empty($routes )) {
                $data[] = '<?php if ( ! defined(\'BASEPATH\')) exit(\'No direct script access allowed\');';
    
                foreach ($routes as $route) {
                    $data[] = '$route[\'' . $route['uri'] . '\'] = \'' . $route['controller'] . '/' . $route['action'] . '\';';
                }
                $output = implode("\n", $data);
    
                write_file(APPPATH . 'cache/routes.php', $output);
            }
        }
    

    If you are adding new routes in an admin area, just run the above function each time you submit your new route and it will re-generate your routes cache file.

    This method keeps your routes in application/config/routes.php intact, but allows you to write new routes to the cache file, without drastically affecting the performance of the site.

    Hope that helps!!