Virtual file extensions hook for CodeIgniter

Derek Jones edited this page Jul 5, 2012 · 7 revisions
Clone this wiki locally

**Hi **CodeIgniters programmers here I wanna make my own routing procedure for improving the Ajax programing arquitecture. Like I didn't care to reinvent the wheel, I looked for something of this kind and found Another AJAX approach from CI in the CodeIgniter Wiki; and I think this was very good for starting; but I needed more to specify several formats althought this archives wouldn't exists but simulated by a PHP, for having variables outputs (Ajax could be Xml o Json for example), so I decided to do my own mapping routine. So you have to change the original Router.php for the new one..., like this...

Original: \system\libraries\Router.php

// Is there a URI string? If not, the default controller specified in the "routes" file will be shown.
if ($this->uri->uri_string == '')

Newone: \system\libraries\Router.php

//Start the looking for formats 
$this->format=EXT;        //The default format is .php
foreach($FORMATS as $format)
 if (stripos($filename=substr($this->uri->uri_string,- (strlen($format)+2)),".$format"))
            //Set the format
            $this->format = $format;
            //extracts the virtual extension to the last variable
            $this->uri->uri_string = str_ireplace(".$format",'',$this->uri->uri_string);
//Finish looking for formats

// Is there a URI string? If not, the default controller specified in the "routes" file will be shown.

if ($this->uri->uri_string == '')

This is useful for asking our application for an specific filenames with their extension, but ended is php whos create the content dynamically. This new Routing hook allow us to ask to a query to be json (for example) like it would be a .json file like:


The routing will clean this URL to:


And will put the $CI->router->format to the specific format. The formats I care in this example: [u] json js xml pdf [/u]

So we could decide to show the wanted output like for example return a json outoput or a table made in html, like this:

//Controller function example
function get_data()
$data['title']="Polymorphic urls behavior";
$query=$this->Testmodel->get_data();   //return an array with the data
 case 'json':
echo   encode_to_json($query)    //this is a helper function
$this-load->view('generic_tables',$data);  //The html standard output (.php archives)

This is a example of a functionality that’s could be request by ajax or by a normal request(html). Not all functions could need this issue, only use it when you have different ways to output this; for example some function will have the case 'xml': instruction for "based xml Ajax call" or for a regular RSS and the arguments defines the rest. Thanks to anybody who reads this article, I hope it would be useful for you. I will thanks feedback to []me[/email]. Greetings,(EliuX)