CodeIgniter - Generate routes dynamically
i have a website with a dynamic navigational menu. I keep the controller (portuguese) names in a database, together with the translation to english.
I want to know if it is possible to affect the 'route' array at runtime, so it would create those routes and cache it when the p开发者_如何转开发age is loaded.
I hope I was clear enough, thanks for the help
You could do this:
Create a table named Routes
--
-- Table structure for table `Routes`
--
CREATE TABLE IF NOT EXISTS `Routes` (
`idRoutes` int(11) NOT NULL AUTO_INCREMENT,
`Order` int(11) NOT NULL,
`Url` varchar(250) NOT NULL,
`Url_Variable` varchar(20) NOT NULL,
`Class` text NOT NULL,
`Method` text NOT NULL,
`Variable` text NOT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`idRoutes`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=67 ;
Create a file in the config directory named pdo_db_connect.php
Put this inside and change accordingly.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function pdo_connect(){
try{
// Include database info
include 'database.php';
if(!isset($db)){
echo 'Database connection not available!';
exit;
}
$dbdriver = $db['default']['dbdriver'];//'mysql';
$hostname = $db['default']['hostname'];//'localhost';
$database = $db['default']['database'];//'config';
$username = $db['default']['username'];//'root';
$password = $db['default']['password'];//'password';
//to connect
$DB = new PDO($dbdriver.':host='.$hostname.'; dbname='.$database, $username, $password);
return $DB;
}catch(PDOException $e) {
echo 'Please contact Admin: '.$e->getMessage();
}
}
Now in your routes file you can do this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// Include our PDO Connection
include('application/config/pdo_db_connect.php');
class dynamic_route{
public $pdo_db = FALSE;
public function __construct(){
}
private function query_routes(){
try{
$routes_query = $this->pdo_db->query('SELECT * FROM Routes ORDER BY `Order` ASC');
if($routes_query){
$return_data = array();
foreach($routes_query as $row) {
$return_data[] = $row;
}
return $return_data;
}
}catch(PDOException $e) {
echo 'Please contact Admin: '.$e->getMessage();
}
}
private function filter_route_data($data){
$r_data = array();
foreach($data as $row){
$return_data = new stdClass;
if(empty($row['Url_Variable']) ){
$return_data->url = $row['Url'];
}else{
$return_data->url = $row['Url'].'/'.$row['Url_Variable'];
}
if(empty($row['Method']) && empty($row['Variable']) ){
$return_data->route = $row['Class'];
}elseif(!empty($row['Method']) && empty($row['Variable']) ){
$return_data->route = $row['Class'].'/'.$row['Method'];
}elseif(!empty($row['Method']) && !empty($row['Variable']) ){
$return_data->route = $row['Class'].'/'.$row['Method'].'/'.$row['Variable'];
}
$r_data[] = $return_data;
}
return $r_data;
}
public function get_routes(){
$route_data = $this->query_routes();
$return_data = $this->filter_route_data($route_data);
return $return_data;
}
}
$dynamic_route = new dynamic_route;
// Give dynamic route database connection
$dynamic_route->pdo_db = pdo_connect();
// Get the route data
$route_data = $dynamic_route->get_routes();
//Iterate over the routes
foreach($route_data as $row){
$route[$row->url] = $row->route;
}
Remember that the routes file is just a PHP file that contains an array, so if you want to get your "Hacker" t-shirt on you could easily do something a little bit dirty.
Have your CMS/application/web-app/fridge-monitoring-system/whatever to have an interface which creates and stores records in a database. Then whenever you save, throw this content into application/cache/routes.php.
Lastly you just have your main routes.php include the cached version and you're good to go.
Yes you can take a look here:
- http://ellislab.com/forums/viewthread/185154/
- http://ellislab.com/forums/viewthread/182180/
You need the following.
One controller like this which will save your routes to a file called "routes.php" in the application/cache folder:
public function save_routes()
{
// this simply returns all the pages from my database
$routes = $this->Pages_model->get_all($this->siteid);
// 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->result_array() as $route) {
$data[] = '$route["' . $this->_get_route($route['pageid']) . '"] = "' . "pages/index/{$route['pageid']}" . '";';
}
$output = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n";
$output .= implode("\n", $data);
$this->load->helper('file');
write_file(APPPATH . "cache/routes.php", $output);
}
}
Here's the second function you will need. This one and the one prior will both go in your application controller which handles your pages:
// 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["parentid"] != 0)
$prefix = $this->_get_route($page["parentid"]) . "/" . $page['page_name'];
else
$prefix = $page['page_name'];
return $prefix;
}
In your Pages_model you will need something along this line:
function get_page($pageid) {
$this->db->select('*')
->from('pages')
->where('pageid', $pageid);
$query = $this->db->get();
$row = $query->row_array();
$num = $query->num_rows();
if ($num < 1)
{
return NULL;
} else {
return $row;
}
}
And this:
function get_all($siteid) {
$this->db->select('*')
->from('pages')
->where('siteid', $siteid)
->order_by('rank');
;
$query = $this->db->get();
$row = $query->row_array();
$num = $query->num_rows();
if ($num < 1)
{
return NULL;
} else {
return $query;
}
}
Every time a page is created, you'll need to have this line executed so I suggest putting it at the end of the controller after all the dirty work is done:
$this->save_routes();
All this together will make you a sweet routes file that will be constantly updated whenever things change.
Something not overly complex, and it keeps the URLs friendly:
inside of routes.php:
// Routes from the database
require_once (BASEPATH .'database/DB.php');
$db =& DB();
// slug will be something like
// 'this-is-a-post'
// 'this-is-another-post'
$sql = "SELECT id, slug FROM items";
$query = $db->query($sql);
$result = $query->result();
foreach( $result as $row )
{
// first is if multiple pages
$route["$row->slug/(:num)"] = "item/index/$row->id";
$route["$row->slug"] = "item/index/$row->id";
}
This assumes 'id' as a primary key and that 'slug' will be unique
Inside your controller, you can obtain the id by:
$id = $this->uri->rsegment(3);
精彩评论