Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP spl_autoload_register

I am trying to take advantage of autoloading in PHP. I have various classes in different directories, and so I have bootstrapped the autoloading as follows:

function autoload_services($class_name) {     $file = 'services/' . $class_name. '.php';     if (file_exists($file))     {         require_once($file);     } }  function autoload_vos($class_name) {     $file = 'vos/' . $class_name. '.php';     if (file_exists($file))     {         require_once($file);     } }  function autoload_printers($class_name) {     $file = 'printers' . $class_name. '.php';     if (file_exists($file))     {         require_once($file);     } }  spl_autoload_register('autoload_services'); spl_autoload_register('autoload_vos'); spl_autoload_register('autoload_printers'); 

It all seems to work fine, but I just wanted to double check that this is indeed considered acceptable practise.

like image 289
JonoB Avatar asked Sep 14 '10 15:09

JonoB


2 Answers

Sure, looks good. The only thing you might do is register them in the order they're most likely to hit. For example, if your most commonly used classes are in services, then vos, then printers, the order you have is perfect. This is because they're queued and called in-order, so you'll achieve slightly better performance by doing this.

like image 127
mr. w Avatar answered Sep 23 '22 06:09

mr. w


You could use:

set_include_path(implode(PATH_SEPARATOR, array(get_include_path(), './services', './vos', './printers'))); spl_autoload_register(); 

Using spl_autoload_register without arguments will register spl_autoload which will look for the class name in the directories of the include path. Note that this will lowercase the class name before looking for it on the filesystem.

like image 29
NikiC Avatar answered Sep 21 '22 06:09

NikiC