• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using SPL_AUTOLOAD_REGISTER

#1
[eluser]Unknown[/eluser]
Hi there !

I need help in the following problem, i have about 50 models in the models directory.
These models represent data in xml files, i was using the spl_autoload_register like this:

Code:
function solap_auto_require($class) {
   if(!strstr($class, 'CI') && !stristr($class, 'PEAR')) {
     @require_once(APPPATH."models/{$class}.php");
   }
}
spl_autoload_register('solap_auto_require');

Which was working fine, until i decided to organize the models, and put them into different folders.

I changed the function to:

Code:
function solap_auto_require($class) {
   if(!strstr($class, 'CI') && !stristr($class, 'PEAR')) {
     @require_once(APPPATH."models/folder1/{$class}.php");
     @require_once(APPPATH."models/folder2/{$class}.php");
     @require_once(APPPATH."models/folder3/{$class}.php");
   }
}
spl_autoload_register('solap_auto_require');

And my application just stopped working.

Any thoughts ?

#2
[eluser]Seppo[/eluser]
Probably the class does not exists on all folders, and you are using require, so the first failure to include a file will die, and the @ won't let you see the error. May be you can try this one.

Code:
function solap_auto_require($class) {
    if(stripos($class, 'CI') === FALSE && stripos($class, 'PEAR') === FALSE) {
        foreach (array('folder1', 'folder2', 'folder3') as $folder)
        {
            if (is_file(APPPATH."models/{$folder}/{$class}.php"))
            {
                include_once APPPATH."models/{$folder}/{$class}.php";
            }
        }
    }
}
spl_autoload_register('solap_auto_require');

#3
[eluser]Unknown[/eluser]
So the problem was because i was using require_once, instead of include_once.
I changed my code according to your suggestion and now it works fine.

Code:
function solap_auto_require($class) {
    if(stripos($class, 'CI') === FALSE && stripos($class, 'PEAR') === FALSE) {
        @include_once(solap_classes."folder1/$class.php");
        @include_once(solap_classes."folder2/$class.php");
    }
}
spl_autoload_register('solap_auto_require');

Thank you very much for your help Smile

#4
[eluser]Rick Jolly[/eluser]
Using class naming conventions would help avoid the overhead of either using multiple includes, or checking if a file exists. Take a look at pear or the zend framework classes. Class names are hierarchical and seperated by underscores to match the class' file path. The autoload method just replaces the underscores with directory seperators to get the file path.

For example:
Code:
class Zend_Acl_Role
// translates to
Zend/Acl/Role.php


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.