CI How-to: Load global data in a view across all controllers
One the first issues I encountered with CodeIgniter was that I wanted to be able to use the same dynamic data in my header view across all controllers. And, I didn't want to repeat myself in each controller to load the model data that needed to be persistent site wide. For example, see the twitter feed in the header? I didn't want to have to do something like this in each method of every controller.
// *** inside the blog controller
function index() {
$data['twitter'] = $this->twitter->get_twitter_status();
return $this->load->view('entry_list', $data);
}
function entry() {
$data['twitter'] = $this->twitter->get_twitter_status();
return $this->load->view('entry_detail', $data);
}
// *** inside the about controller
function index() {
$data['twitter'] = $this->twitter->get_twitter_status();
return $this->load->view('about', $data);
}
// *** etc...
There is too much repetition here, so let's streamline the process. Start by creating a file in ./system/application/libraries/MY_Controller.php. When you prefix it with "MY_", CI will automatically load the file because it thinks you want to extend the base class. We do. Win.
class MY_Controller extends Controller {
var $global_data = array();
function MY_Controller() {
parent::Controller();
$this->load->model('Twitter_model', 'twitter');
$this->global_data['twitter'] = $this->twitter->get_twitter_status();
// other common stuff; for example you may want a global cart, login/logout, etc.
}
// create a simple wrapper for the CI load->view() method
// but first, merge the global and local data into one array
function display_view($view, $local_data = array()) {
$data = array_merge($this->global_data, $local_data);
return $this->load->view($view, $data);
}
}
Now in your controllers, extend MY_Controller instead of Controller. And in your controller methods, instead of calling $this->load->view(), call the wrapper function.
class Blog extends MY_Controller {
function Blog() {
parent::MY_Controller();
}
function index() {
$data['will_it_blend'] = "Yes, it will blend.";
// ... do stuff ...
$this->display_view("entry_list", $data);
}
}
The "entry_list" view in this example will have both the global $twitter and the local $will_it_blend data variables set. While trolling the CodeIgniter forums, I also came across Template Library for CodeIgniter which looks to be even more über. But I think it might be overkill for what I'm after today.
