Search code examples
phpcodeigniterpackageautoloadautoloader

Why isn't CodeIgniter autoloading my package?


In my application/config/config.php, I want to autoload my library package:

/*
| -------------------------------------------------------------------
|  Auto-load Packges
| -------------------------------------------------------------------
| Prototype:
|
|  $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/

$autoload['packages'] = array('../../lib');

The relative path did not work, so I got the current directory of my index.php and tried that:

$autoload['packages'] = array(getcwd() . '/../../lib');

Finally, I just stuck the absolute path in there:

$autoload['packages'] = array('/Users/.../lib');

None of these worked. Am I missing something? Because the documentation is quite sparse.


Solution

  • To fix this I added a modified autoloader right before the require_once statement in index.php:

    spl_autoload_register(function($class) {
        if (strstr($class, 'CI') || strstr($class, 'MY')) {
            return;
        }
    
        $class = ltrim($class, '\\');
        $filename  = '';
        $namespace = '';
    
        if ($last_ns_pos = strripos($class, '\\')) {
            $namespace = substr($class, 0, $last_ns_pos);
            $class = substr($class, $last_ns_pos + 1);
            $filename  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
        }
    
        $filename .= str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
    
        require strtolower($filename);
    });
    

    The original autoloader can be found here.

    Honestly, no matter what I tried with CodeIgnitier, loading third-party packages or drivers just would not work.