Database driven routes in CodeIgniter with caching
A faster, simpler and easier solution to database driven routes in CodeIgniter.
Don't know what I'm on about? Read my previous article on database driven routes.
Prerequisites
Step 1
Define 3 new methods in your routes model (..system/application/models/route.php).
function save()
{
parent::save();
$this->cache();
}
function delete()
{
parent::delete();
$this->cache();
}
/**
* Writes contents of database table to a cache file.
*
* @return void
*/
function cache()
{
$data[] = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');";
foreach($this->get()->all as $value)
{
$data[] = '$route["' . $value->route . '"] = "' . $value->controller . '";';
}
$output = implode("\n", $data);
write_file(BASEPATH . "cache/routes.php", $output);
}
This will write the contents of the routes table as a PHP array to a file called routes.php in the cache folder (make sure this folder is writeable). This file will be deleted an rebuilt whenever an insert, update, or delete operation is performed on the routes database table.
Step 2
Insert the code below into the routes.php file ( ..system/application/configs/routes.php ) after the scaffolding trigger.
include_once BASEPATH . "cache/routes.php";
If anyone implemented the original solution let me know what you think of this in the comments.
Comments
No comments yet!