We did create more than one base controller. But what about MY_Controller? Why do we need it? MY_Controller sets the basic parameters for every controller in your application. That is why even the Admin_Controller and Public_Controller extends MY_Controller and not CI_Controller.
“What can it be so basic that an Admin_Controller and a Public_Controller couldn’t handle?” I hear you say. Well let’s start with the simplest thing… a generic title for all our pages. Also, let’s just think a bit about what usually happens when you talk about MVC in general and CodeIgniter in particular. Usually, when someone will visit your site, your controller would go ask the database (with the help of a model) for some specific information and store that information inside a $data array. After that, the controller will pass the $data array to the view that will use it to display the information. Right? But what if, because the model didn’t return any information, the $data array won’t be initialized? Then you will have a big error on your site. So we will have to at least initialize the $data array. And what better method to initialize the array than populating it with the generic title of the page?
So let’s make our basic MY_Controller.php by initializing the $data array:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Controller extends CI_Controller { protected $data = array(); function __construct() { parent::__construct(); $this->data['pagetitle'] = 'My CodeIgniter App'; } }
And… that’s it. After this, whenever you will have to store and pass data, the only difference would be to do it within a $this->data array;
So in a method, you would only have to call it as:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends MY_Controller { function __construct() { parent::__construct(); } public function index() { // I sure hope that you will interpret what you see below just as an example of use... $this->load->model('whatever_model'); $this->data['whatever'] = $this->whatever_model->get(); $this->load->view('your_view',$this->data); } }
“That is ugly as hell…”, you might say… Yes, but improving this will be part of another step: Using templates in CodeIgniter.
Hi there.
I’ve been playing around with this code to understand how to use global variables throughout my views via a controller based on MY_CONTROLLER.
It does not appear to make any difference if I declare the protected $data array not, as long as I declare the variables that I want in the constructor of MY_Class
What is the point of the protected $data = array(); ?
Thanks for your help.
You can define an array by calling array(). You can also define an array by defining a key and a variable. But if you define an empty array, you make sure that if no keys and/or values are inserted into that array you still have an empty array available.