Welcome Guest, Not a member yet? Register   Sign In
Does CI have a application wide controller?
#1

[eluser]Unknown[/eluser]
I am new to Codeigniter and i was wondering if CI had a controller that was available site wide. Something like Ruby on Rails' application controller. I even think Cakephp has an application controller.

If Codeigniter does not have an application controller, how do i go about making methods available throughout the entire site?

Thanks in advance for any and all information.
#2

[eluser]danmontgomery[/eluser]
This is covered in the user guide, under "Extending Core Class"
#3

[eluser]treeface[/eluser]
The best way of making methods available throughout the entire site is to use either libraries or helpers. A helper is basically a global PHP function that you can call at any time in your script as long as its been loaded in. I do this, for example, as an "isAdmin()" check where my isAdmin helper function looks like this:

Code:
/**
* isAdmin
*
* Determines if the current user is an administrator
*
* @access    public
* @param    void
* @return    boolean
*/
if ( ! function_exists('isAdmin')) {
    function isAdmin() {
        $CI =& get_instance();
        
        return $CI->UserM->isAdmin();
    }
}

So you can see that I first get an instance of the CI superobject, then use that to access my User model where I have a function that compares the session userdata to the database and returns a boolean value. Then as long as I've declared this helper in my helper config file, anywhere in my code I can do this:

Code:
if ( isAdmin() )
{
    //do stuff
}

A library works about the same, except you have to either autoload it in the autoload config file or load it in at any time like this:

Code:
$this->load->library('mylibrary');
$this->mylibrary->myFunction();

Look up these sections in the user guide because they explain it way better than I can.
#4

[eluser]jedd[/eluser]
Hi T-wrecks and welcome to the CI forums.

This stuff, in addition to being covered in the user guide, is also discussed in the [url="/wiki/FAQ"]FAQ[/url] - the question about repeating lumps of code (Design section).

It also has its own page - [url="/wiki/MY_Controller"]MY_Controller[/url] in the wiki.
#5

[eluser]jedd[/eluser]
For the record, my understanding is that you should (for various values of 'should') try to avoid calling the CI superobject in Helpers.

An is_admin() function, if used in very many of your controllers, or perhaps being used to do 'stuff' prior to a given controller being launched, is a good candidate for MY_Controller.
#6

[eluser]pickupman[/eluser]
See the post on Phil Sturgeon's website for Base Controllers linked in my signature, and welcome to the forums.




Theme © iAndrew 2016 - Forum software by © MyBB