0

The problem I am facing is that spl_autoload($class) passed in spl_autoload_register callback, will not load classnames which refer to the same filename, but in different directories.

What I want to achieve is using spl_autoload, not using require and without namespaces, to load automatically following classes:

%Project_Path%/controllers/test.php:

class TestController {

}

%Project_Path%/models/test.php:

class TestModel {

}

What I'm doing is replacing the Controller or Model suffix in the classname with empty string, so it will get the filename class Test lowercased is test, and adding the spl extension php should go to test.php.

In the beginning of the file, I have set the include path to refer either to pear, to current directory, to models directory and to controllers directory.

If there are question, what have I tried - this is what I have tried :) spl_autoload() is not recieving paths, so I have to change the include path in order to include the files.

I succeed in achieving it with require and the explicit path, then the classname, but I was in doubt if it's possible with spl_autoload following the current pattern, without changing filename, classname or adding namespace

Royal Bg
  • 6,988
  • 1
  • 18
  • 24

1 Answers1

0

you can try a function like file :XProject.class.php:

class XProject{
    public static function autoload($class) {
        //echo '>> auto load >'.$class.'<br>';

        if (file_exists(BASEPATH . 'core/lib/' . $class . '.class.php')) {
            require_once(BASEPATH . 'core/lib/' . $class . '.class.php');
        } elseif (file_exists(BASEPATH . 'core/utils/' . $class . '.class.php')) {
            require_once(BASEPATH . 'core/utils/' . $class . '.class.php');
        }
    }
}

and :

include BASEPATH.'core/lib/XProject.class.php';
spl_autoload_register('XProject::autoload');

inthis example I supposed %Project_Path% as BASEPATH. hope this code will help you.

Mimouni
  • 3,564
  • 3
  • 28
  • 37
  • Your function is using `require` instead of `spl_autoload` – Royal Bg Nov 28 '13 at 12:24
  • You did not understand me. Check again my first sentence in the question. In spl_autoload_register I pass in the callback all that is needed to make $class real filename and then pass it to spl_autoload(). No require/include/require_once – Royal Bg Nov 28 '13 at 12:55