Well... I'm out of ideas on what to write about. Do you have any ideas? Please, write me in any comment section you find, and I will do my best to tell you about that particular subject

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:

MY_Controller.php

PHP

1

2

3

4

5

6

7

8

9

10

11

<?phpdefined('BASEPATH')ORexit('No direct script access allowed');

classMY_ControllerextendsCI_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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?phpdefined('BASEPATH')ORexit('No direct script access allowed');

classWelcomeextendsMY_Controller{

function__construct()

{

parent::__construct();

}

publicfunctionindex()

{

// I sure hope that you will interpret what you see below just as an example of use...

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.