Home

Advertisement

Customize

Aug. 26th, 2008

CodeIgniter - A neat trick

This one came out of a small IRC brainstorm the other day and it turned out to be quite a useful tip for all you codeIgniter developers. I'll lay down the ground work for you and you can take it from there.



There are many ways of using views in CI. Some people like to call them directly in their controllers, others prefer to attribute them to variables and centralize them in a single layout file. I am kind of in the first category.

I actually got the habbit of adding a function such as _buildPage() or something like that in my controller that allows me to re-use most of the layout stuff with a minimum of coding.



A typical controller would look something like this...

class Home extends Controller {
 function _buildPage($content,$data){
   $this->load->view('header',$data);
   $this->load->view($content,$data);
   $this->load->view('footer',$data);
 }
 function index(){
   // ... all the code required by index
   // call the display
   $this->_buildPage('index',$data);
 }
 function listing(){
   // ... all the code required by listing
   // call the display
   $this->_buildPage('listing',$data);
 }



This is fine for most cenarios, but sometimes, you need more mobility... let's assume that you have 20 controllers, and that suddenly, you need to add a "publicity" layout just below the header, and that this publicity layout is directly related to the controller action you are calling...

There you go, editing 20 php files, making modifications... needless to say, a boring job.



Here comes the neat trick.

Instead of placing the _buildPage in the controller, extend the basic controller object for CI. Create you different layout calls there... here's a sample of an extending controller and a class using it:



in you application/libraries folder, add a "MY_controller.php" file.

It's contents should read something like this:



php
// we create a new MY_class that extends the basic Controller class;
// MY_ is the default prefix for classes that should extend/override CI classes (it can be
// customized in the config file.
class MY_Controller extends Controller {
	// this is my _buildPage function that loads a specific view with all the extra views I may need.
	function _buildPage($view="",$data){
		$this-load->view('header',$data);
		$this->load->view($view,$data);
		$this->load->view('footer',$data);
	}
}
?>



The same example above, using the new controller class:



class Home extends MY_Controller {
 function index(){
   // ... all the code required by index
   // call the display
   $this->_buildPage('index',$data);
 }
 function listing(){
   // ... all the code required by listing
   // call the display
   $this->_buildPage('listing',$data);
 }




With minor tweaks, you can easily control all sorts of layouts. The best of all, it's all central in a single file.


Advertisement

Customize