Step 11 – Creating and working with the famous MY_Controller

Created at: January 8, 2015; Last update: July 28, 2016

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:

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:

“That is ugly as hell…”, you might say… Yes, but improving this will be part of another step: Using templates in CodeIgniter.

2 thoughts on “Step 11 – Creating and working with the famous MY_Controller

  1. JB

    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.

    Reply
    1. avenirer Post author

      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.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

No spam? * Time limit is exhausted. Please reload CAPTCHA.