I find that collecting data throughout controller can get a bit disorganized, especially if you have more than one method involved. Instead of collecting view data separately in each method it’s easier to store data in a single controller attribute. Once all of the template data are stored in a single attribute, we can also simplify the process of rendering views by adding a method that automatically passes the above data array to a view.

//attribute for view data
protected $data = array();

//our new method for view output
protected function render($template){
	$this->load->view($template, $this->data);
}

//a tipical controller method
public function index(){
	$this->data['post_name'] = 'Post name';
	$this->data['post_text'] = 'Post text';
	$this->render('welcome_message');
}

As you can see, this approach not only simplifies, but also unifies the way to handle view data. Personally, I would like to see something like this built into the core controller. Until that happens it’s a good idea to extend the core controller with this functionality. In fact, you should almost always extend CodeIgniter’s core controller, since it will give you the ability to add functionality as your application grows.


There are no comments yet. Be the first to leave one.


Leave a Reply


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>