Welcome Guest, Not a member yet? Register   Sign In
Database Driven Routes without hooking or datamapper [UPDATED]
#1

[eluser]ranjudsokomora[/eluser]
Look at replies for updated code

Good Day CI Coders,
I was looking for dynamic route building the other day on here and found http://ellislab.com/forums/viewthread/121486

Here is my version of the above without building a hook, or using DataMapper:
I removed EllisLabs comments because I couldn't post on the forum with them include.
You can always look at them by opening /system/libraries/router.php

Code:
<?PHP IF ( ! defined('BASEPATH')) exit('No direct script access allowed');
# REMOVED EllisLab Comments to save space, to view comments
# open /system/libraries/router.php
class MY_Router extends CI_Router
{
    var $database_connects = array();
    var $route_conn_now        =    array();
    
    function MY_Router()
    {
        parent::CI_Router();
    }
    
    function _set_routing()
    {
        if ($this->config->item('enable_query_strings') === TRUE AND isset($_GET[$this->config->item('controller_trigger')]))
        {
            $this->set_class(trim($this->uri->_filter_uri($_GET[$this->config->item('controller_trigger')])));
            if (isset($_GET[$this->config->item('function_trigger')]))
            {
                $this->set_method(trim($this->uri->_filter_uri($_GET[$this->config->item('function_trigger')])));
            }
            return;
        }
        
        @include(APPPATH.'config/routes'.EXT);
        # If you want all your routes to come from a database remove the above line
        # Keep in mind your database must contain the default route(s) or CI will not function.
        
        ## Code Authored By: Ranjudso Komora
        // Load the database.php file.
        @include(APPPATH.'config/database'.EXT);
        $this->database_connects    =    (!isset($db) OR !is_array($db)) ? array() : $db;
        
        IF (!EMPTY($this->database_connects))
        {
            $this->route_conn_now    =     (ISSET($this->database_connects['router'])) ? $this->database_connects['router'] : $this->database_connects['default'];
            SWITCH (trim($this->route_conn_now['dbdriver']))
            {
                case "mysql";
                    $link = mysql_connect($this->route_conn_now['hostname'], $this->route_conn_now['username'], $this->route_conn_now['password']);
                    IF (!$link)
                    {
                        $error_message    =    "An error occured connecting to your database host<br />Check your connection setttings.";
                        show_error($error_message);
                    }
                    $db        =    mysql_select_db($this->route_conn_now['database']);
                    IF (!$db)
                    {
                        $error_message    =    "An error occured connecting to your database.<br />Check your connection settings.";
                        show_error($error_message);
                    }
                    $mysql        =    "SELECT * FROM tblRoutes";
                    $my_query    =    mysql_query($mysql);
                    IF (!$my_query)
                    {
                        $error_message    =    "An error occured while trying to query your database.";
                        show_error($error_message);
                    }
                    while ($data = mysql_fetch_assoc($my_query))
                    {
                        $route[trim($data['vchRoute'])]    =    trim($data['vchController']);
                    }
                break;
            }
        }
        
        #End Of Custom Code
        
        
        $this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route;
        unset($route);
        $this->default_controller = ( ! isset($this->routes['default_controller']) OR $this->routes['default_controller'] == '') ? FALSE : strtolower($this->routes['default_controller']);    
        $this->uri->_fetch_uri_string();
        if ($this->uri->uri_string == '')
        {
            if ($this->default_controller === FALSE)
            {
                show_error("Unable to determine what should be displayed. A default route has not been specified in the routing file.");
            }
            
            if (strpos($this->default_controller, '/') !== FALSE)
            {
                $x = explode('/', $this->default_controller);
                $this->set_class(end($x));
                $this->set_method('index');
                $this->_set_request($x);
            }
            else
            {
                $this->set_class($this->default_controller);
                $this->set_method('index');
                $this->_set_request(array($this->default_controller, 'index'));
            }
            $this->uri->_reindex_segments();
            log_message('debug', "No URI present. Default controller set.");
            return;
        }
        unset($this->routes['default_controller']);
        $this->uri->_remove_url_suffix();
        $this->uri->_explode_segments();
        $this->_parse_routes();        
        $this->uri->_reindex_segments();
    }
}

Save the above as MY_Router.php in your /application/libraries folder.

If you routes are stored in a separate database from your default database you will need to create a new database array with the name of "router" and set the appropriate information.

I built the above with a SWITCH statement, but only put the logic for MYSQL in. It should be easy for anyone to use other database engines, as you would just need to add a case statement and logic for your dbdriver type.

My scheme for MYSQL
Code:
CREATE TABLE `tblRoutes` (
  `vchRoute` VARCHAR(250) NOT NULL,
  `vchController` VARCHAR(250) NOT NULL
)


Messages In This Thread
Database Driven Routes without hooking or datamapper [UPDATED] - by El Forum - 05-27-2010, 09:32 AM



Theme © iAndrew 2016 - Forum software by © MyBB