CodeIgniter Forums

Full Version: Autoload a class?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys.

I am new to codeigniter.

I want to make my own App_Controller and extend all other controllers from this.
I want to put it in controllers folder.

But is not working.
class Welcome extends App_Controller { 
is not finding it even if they are in the same contorller?

There is no such thing as loading a file by its class name?

I looked at
Looks like my only hope is to put my App_Controller in core and init that in my config or smth?

I really think there should be an autoloader to look files by class name that is a big surprise for me not to find. 
Or is there a way?

You are right, you have to put App_controller.php in application/core folder, and update application/config/config.php setting $config['subclass_prefix'] = 'App_';

Autoloading is a bit tricky. You don't want to scan through every potential folder and sub-folder, because that would make every request to your site very slow. Placing it in application/controllers folder also causes issue with auto-routing - you would now have technically available, etc.

I have't checked how CI4 handles this yet myself (which I really ought to), but that's how CI3 works, and it's not that unreasonable.
thanks Pertii
If you have more then one custom controller, you can use this spl autoloader for them.

Just add it at the bottom of your ./application/config/config.php file.

PHP Code:
// -----------------------------------------------------------------------

 * SPL Autoloader - using an anonymous function as of PHP 5.3.0
 * -----------------------------------------------------------------------
 * @author InsiteFX - Raymond L King Sr.
 * Place this code at the bottom of your ./application/config/config.php
 * file.
spl_autoload_register(function ($class) {

    if (
strpos($class'CI_') !== 0)
        if (

Hope that helps.
Here is a page - one part of a larger tutorial - that examines the multiple ways to add autoloading to CodeIgniter.

I prefer the "hook" method myself. (Don't worry, that will make sense once you read the page.)
I'm pretty sure the code for that approach is tucked away on the forum somewhere.
(11-29-2018, 08:36 AM)Pertti Wrote: [ -> ]I have't checked how CI4 handles this yet myself (which I really ought to)

Yes, you really should. (Spoiler Alert: namespaces and a PSR-4 compliant autoloader)
(11-29-2018, 01:54 PM)dave friend Wrote: [ -> ]Yes, you really should.

Tidying up my home office / warehouse over Christmas, and then I'll be on it Smile
CI 4 uses the PSR-4 autoload. You just need to setup your paths to your libs.