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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With