Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple spl_autoload_register issue

I'm working on the development of a custom framework. And I have encountered an issue when I tried to dynamise the calling of my classes.

This is a visual of my files :

enter image description here

So I decided to create a different function for each folder (libs, controllers et modeles):

function autoloadLibs($class) {
    //require the general classes
    require 'libs/' . $class . '.php';
}

function autoloadModels($class) {
    //require the models classes
    require 'models/' . $class . '.php';
}

function autoloadControllers($class) {
    //require the controllers classes
    require 'controllers/' . $class . '.php';
}

spl_autoload_register ('autoloadLibs');
spl_autoload_register ('autoloadControllers');  
spl_autoload_register ('autoloadModels');

Nevertheless I have this message : Warning: require(libs/admin.php): failed to open stream, of cours it's not the good folder. But I don't know how to fix that. Is there a good way to optimise my classes calls ?

like image 639
Adrien G Avatar asked Oct 16 '12 11:10

Adrien G


2 Answers

After few tests, I found this solution for my case :

set_include_path(implode(PATH_SEPARATOR, array(get_include_path(), './libs', './controllers', './models')));
spl_autoload_register();
like image 61
Adrien G Avatar answered Sep 19 '22 08:09

Adrien G


You need to check the file exists first with is_file() before you attempt to require it.

When using spl_autoload_register(), I've found it's generally better to register one method to include the files. The fact that you can bing multiple functions I believe is to make interoperability with different libraries easy (so they don't clobber __autoload()). It will also save you having to write the code out multiple times to check for the file's existent, map _ to directory separator (if you do that), etc.

So, assuming you change your filenames to suit the convention of Underscore_Separated_Name, e.g. Controller_Admin_Dashboard, you could use...

function autoload($className) {

    $path = SYSPATH .
            str_replace("_", DIRECTORY_SEPARATOR, strtolower($className)) . 
            ".php";

    if (is_file($path)) {
        require $path;
    }

}

The first time you instantiate Controller_Admin_Dashboard, PHP may include a file such as /app/controller/admin/dashboard.php.

like image 21
alex Avatar answered Sep 22 '22 08:09

alex