Skip to content

MY Controller how to extend the CI Controller

World Wide Web Server edited this page Jul 4, 2012 · 8 revisions

A frequently asked question is 'how do I do something for every controller / page?', with the implied caveat - 'without having to replicate a chunk of code into every controller'.

There are a number of places and ways to do this (hooks, libraries, etc) but this article looks at one just one - extending the CI Controller. This is described briefly in the CI User Guide - specifically on the [url="http://codeigniter.com/user_guide/general/core_classes.html"]Core Classes[/url] page, and it would be good to familiarise yourself with that information before proceeding.

[h2]MY?[/h2] This functionality is often called [b]MY_Controller[/b] though to be fair you can call it whatever you like. In your [b]config.php[/b] file you can modify this prefix to suit - say the abbreviation for your project, or your name, etc. Remember that everyone else will still refer to it as [b]MY[/b], though.

To change this, edit the config.php and find this line: [code] $config['subclass_prefix'] = 'MY_'; [/code]

.. and change it to something else. Remember, you don't have to do this (and unless you know what you're doing, you probably shouldn't). The rest of this page - indeed all CI documentation - assumes you have not changed this prefix setting.

[h2]Creating the MY_Controller.php[/h2]

This is very straightforward. You create this file in the [b]application/libraries/[/b] directory, and you call it [b]MY_Controller.php[/b]

At a minimum it will contain the following: [code] <?php /** * Extension to CI Controller * * This controller intercept allows * ... * * @author yourname * @package yourpackagename * @version v X.Y * */

class MY_Controller extends Controller {

function MY_Controller ()
{
    parent::Controller();
}

}

/* End of file MY_Controller.php / / Location: ./system/application/libraries/MY_Controller.php */ [/code]

Now, this file as it stands will work, but it doesn't [i]do[/i] anything for us - yet. We'll come back to this shortly.

[h2]Using MY_Controller from YOUR controllers[/h2]

In order to use this new extended controller, your normal controllers need to call this one, rather than the standard CI controller. This is quite straightforward. Whereas you used to start your controller with :

[code]class Foo extends Controller { function Foo () { parent::Controller(); } [/code]

you now start it with :

[code]class Foo extends MY_Controller { function Foo () { parent::MY_Controller(); } [/code]

Note the MY_ prefix in two places there. That's all you need to change in your controllers.

If you have worked through this far with this guide, and you make this change, you'll find that your web pages work [b]exactly[/b] as they did previously - so far we have made a completely transparent modification.

[h2]Endless possibilities[/h2]

Some common usages include - identifying if a user is authenticated (pulling information out of the session data for example), generating sections of pages - especially top-bars or status bars or navigation menus (as per the example below).

Again, keep in mind that this code will get run on every page load - so think carefully about the functionality you end up putting into here. Anything you don't need on [i]every[/i] page should probably not live here.

[h2]An example to wrap this up[/h2]

You probably got to this page because you want to do something specific with this feature. In which case, you can probably wander off and do this now - just add the code into the [b]MY_Controller.php[/b] file, keeping in mind that it will get loaded by every controller from here on - so don't overload the thing!

The example here is straightforward - creating a navigation menu table for later insertion by each controller. The navigation menu is therefore stored, in an array, in the MY_Controller.php file. This may not suit you, indeed it may not be optimal, but it suffices as a demonstration.

A complete, functional, [b]MY_Controller.php[/b] file:

[code] <?php

class MY_Controller extends Controller { // Need to initialise $data before we use it. var $data = array();

function MY_Controller ()  {
    parent::Controller();

    // Having this in a separate, private function, keeps the main code cleaner.
    $tmp_data['menu_data'] = $this->_generate_menu_data();
    
    // $this->data   is used later by normal controller when sending to the primary view file
    $this->data['main_menu_view'] = $this->load->view ('create_table_main_menu', $tmp_data, TRUE);

    } // end-method  Constructor


/**
* Generate the main navigation menu
*
* @access private
* @param  void
* @return $menu_data_array   - for direct feeding to the view
*/
private function  _generate_menu_data ()  {
    $menu_data_array = array (
            "Lobby" => array (
                "Front page"              => "meta/lobby",
                "About this site"         => "meta/about",
                ),
            "People" => array (
                "Browse"                  => "people/browse",
                "Search"                  => "people/search",
                ),
            "Places" => array (
                "Browse"                  => "locations/browse",
                "Search"                  => "locations/search",
                ),
            );
    return ($menu_data_array);
    }

} // end-class

/* End of file MY_Controller.php / / Location: ./system/application/libraries/MY_Controller.php */ [/code]

The view construction file (create_table_main_menu.php) is not shown, but is easy to deduce - a cycle through the array, as shown, generating a snippet of HTML code that starts with

and ends with
. This variable - part of [b]$this->data[/b] will then be visible to your controllers.

That is, within your normal controller, sending $this->data to the view file like this: [code] $this->load->view ('default', $this->data); [/code]

  • will result in the view file having access to a variable called $main_menu_view (along with whatever data you have passed to the view in your $data variable). The $main_menu_view file, though, will simply be echo'd in the right place, and a navigation menu will magically appear on your web page!

-- end of page --

Clone this wiki locally