views:

222

answers:

2

Although I can tentatively see a solution to this, I was wondering if there may be a glaringly obvious simpler approach.

My aim is to use the first segment of a given URI to query the DB as to which controller should be run.

I assume I would have to reform the URI with the resultant controller name in segment 1, then allow the system to continue processing as normal (hence a pre_system hook).

Although not essential I would also like to hold a couple of other variables from the same DB request to be used later in the call stack, and assume this would have to be done using global variables?

Any better suggestions would be gladly received.

Thanks.

A: 

I wouldn't use global variables, Id prefer to store it in a library for retrieval later if possible. Global variables are kind of messy in the context of CI.

Although at pre_system Only the benchmark and hooks class have been loaded at this point. This means you're pretty-much stuck with global variables unless you can find a way to select the controller on pre_controller as all the base-classes are loaded and you can put the data somewhere more logical.

Aren
Hey Aren, pre_controller was my first thought for the reasons you mention. I wasn't going to spend the time delving into the core files to find where the controller selection takes place, but think I may now (after the weekend!). It would be a far more elegant solution if possible.
Andy
I know it's possible to extend any of the base classes. Perhaps you could extend the base-class for controller and assign variables right on the object?
Aren
I've had a look and a play; if I understand correctly, this approach will not work because "The pre_controller hook executes before the super object has been fully constructed." So am now back to original suggestion of pre_system.
Andy
A: 

Should it be of use to anyone else, here is the code to acheive the desired result. This does however not take into account passing additional variables because I can live without them.

function set_controller()
{
    include_once APPPATH.'config/database.php'; //Gather the DB connection settings
    $link = mysql_connect($db[$active_group]['hostname'], $db[$active_group]['username'], $db[$active_group]['password']) or die('Could not connect to server.' ); //Connect to the DB server
    mysql_select_db($db[$active_group]['database'], $link) or die('Could not select database.'); //Select the DB
    $URI = explode('/',key($_GET)); //Break apart the URL variable
    $query = 'SELECT * FROM theDomainTable WHERE domainName = "'.$URI[1].'"'; //Query the DB with the URI segment
    if($results = mysql_fetch_array(mysql_query($query))){ //Only deal with controller requests that exist in the database
        $URI[1] = $results['controllerName']; //Replace the controller segment
        $_GET = array(implode('/',$URI)=>NULL); //Reconstruct and replace the GET variable
    }
    mysql_close($link); //Close the DB link
}
Andy