Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter autoload specific classes

I have created two controllers, the Public_Controller and the Admin_Controller inside ./application/libraries folder, following Phil's Sturgeon example.

What I want to do is to autoload the Public_Controller and Admin_Controller specificly, so I created this autoload function inside ./application/config.php

function __autoload($class) {

    // Autoload only Public_Controller and Admin_Controller
    if (strpos($class, 'CI_') !== 0) {
        $file = APPPATH . 'libraries/'. $class .'.php';
        if ( file_exists($file) && is_file($file) ) {
            @include_once($file);
        }
    }
}

The problem with this I think is that I have more files included inside the libraries folder, so those too are autoloaded, which is not what I want. So instead I tried to do a small change to the first if statement, like this:

if ( in_array($class, array('Public_Controller, Admin_Controller')) ) // instead of strpos

in order to target only these two classes, but this does not seem to work. Any ideas what I might doing wrong?

like image 567
ltdev Avatar asked Mar 07 '14 12:03

ltdev


2 Answers

Go to applications/config/autoload.php and in there you can edit what you need.

They are in arrays and seperated by packages, libraries, helpers, config, languages and models.

eg

$autoload['libraries'] = array('database', 'session');

$autoload['helper'] = array('url', 'html', 'form');
like image 77
Albzi Avatar answered Sep 22 '22 14:09

Albzi


I only wanted to auto load Public_Controller in the frontend and Admin_Controller in admin, so autoload.php is out. In autoload.php the files are loaded globally. The __autoload() function only tries to auto load a class when it's called, but not found.

like image 22
ltdev Avatar answered Sep 25 '22 14:09

ltdev