Autoloading Class Problem With Smarty
If you are using Smarty Template engine with your PHP code and you happen to use an autoloader, then you may have encountered an autoloading class problem with Smarty stating that the file “Smarty_Internal_TemplateBase” can’t be found and your script produces a FATAL error. Smarty is using it’s own autoloader using the spl_autoload_register method and our autoloader is messing it up.
1 2 3 4 5 6 |
//********************************** // autoloader //********************************** function __autoload($class) { include 'classes/' . $class . '.class.php'; } |
The code above will fire automatically for all missing class files and since we are looking for a file inside “classes” directory, it will end up as a missing file due to the fact that the “missing” file is under Smarty’s installed folder.
Easy Manual Fix
We can fix this by expanding our autoloader to include Smarty’s folder and hard coding everything inside.
1 2 3 4 5 6 7 8 9 10 11 |
//********************************** // autoloader //********************************** function __autoload($class) { include 'classes/' . $class . '.class.php'; if (substr($classname, 0, 7) == "Smarty_") { $classname = "Smarty/sysplugins/" . strtolower($class); $status = include_once $classname . ".php"; } } |
It is working ok but what if we need to add another 3rd party framework that have it’s own autoloader?
Easy Permanent Fix
To correct the problem, we need to register our own spl_autoload_register using the code below..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//********************************** // autoloader //********************************** function autoload($class_name) { $status = include_once 'classes/class.' . $class_name . '.php'; if(!$status) { echo "Fatal Error: I cannot load the class $class_name."; die(); } } spl_autoload_register("autoload"); |
We just told PHP to add a new autoloading class function for us named “autoload” which will run parallel with Smarty’s autoloder function.