Question

composer.json:

{
  "require": {
    "smarty/smarty": "v3.1.17"
  }
}

index.php:

define('SMARTY_SPL_AUTOLOAD', 1); // now smarty should use its own autoloader

require_once __DIR__ . "/vendor/autoload.php";

function my_classes_loader($class) {
  $path = "{$class}.class.php";

  if (file_exists($path)) {
    include_once $path;
    return true;
  }

  return false;
}

spl_autoload_register('my_classes_loader');

$smarty = new Smarty();
$smarty->setCompileDir("templates_c");

$smarty->display('main.html');

exit();

If I open it in browser I get

Fatal error: Class 'Smarty_Internal_TemplateCompilerBase' not found in //smarty-example/vendor/smarty/smarty/distribution/libs/sysplugins/smarty_internal_smartytemplatecompiler.php on line XX

The file is there. And it has content. And it is accessible / readable for PHP etc.

What am I doing wrong? What is missing?

Was it helpful?

Solution

It is a good idea to only have one point deciding about autoloading, and this should be Composer alone.

Try to put your own autoload function away, use a autoload declaration in your composer.json instead. Unfortunately you are not using either PSR-0 or PSR-4 naming standard, but Composer allows you to use "classmap" in this case. Consider moving all your file names to comply with PSR-0.

And the smarty autoloading should already be done by requiring it via Composer. No need to set that constant.

Last but not least I think your autoload function should not return anything. Especially it should not return false if it cannot find the file it supposes to contain the class, because depending on how the autoload functions are ordered on the stack, your function might get called first for ALL classes, including all Smarty ones. If you return false in these cases, you destroy the working autoload stack by not allowing later functions to load that class.

So all in all it is best to use Composer for all autoloading. The developers did everything to provide the best performing autoload function - your own function probably can only be as fast as theirs, but will probably be slower.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top