2

We used to include only classes that are stored in a {project_root}/includes folder. And we used autoload function to include classes we need in our apps. Now I wanted to use some library and I faced a problem:

1) Autoload:

// {project_root}/includes/autoLoad.php
// There is a global_connfig.php file that loads by directive in php.ini 
// auto_prepend_file = /var/www/global_config.php which includes autoload.php file and sets the include path to {project_root}/includes
function __autoload($classname){
    include "$classname.php";
}

2) Code I wanted to use:

//just an example from the monolog reference
// I put Monolog folder with it's subfolders in {project_root}/includes
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger("name");
$log->pushHandler(new StreamHandler(LOGSPATH . '/monolog', Logger::WARNING));


$log->warning('Foo');
$log->error('Bar');

3) Errors:

Warning: include(Monolog\Logger.php): failed to open stream: No such file or
directory in {project_root}/includes/autoLoad.php

I tried to use something like this: autoloading classes in subfolders, but still getting Class 'Monolog\Logger' not found

question updated

Community
  • 1
  • 1
Daria
  • 861
  • 11
  • 29

1 Answers1

1

Try this autoload function instead :

function __autoload($classname)
{                                      
    $filename = str_replace("\\", "/", $classname).".php";       
    include __DIR__."/$filename";                                     
}  
  • It replaces \ with / to match paths
  • It searches from the includes/ directory.

You might also consider adding the includes/ path to your include_path php directive :

set_include_path(get_include_path() . PATH_SEPARATOR . "{project_root}/includes");
Thibault
  • 1,566
  • 15
  • 22
  • Woww, that look to remove error I got! Now it's just `Warning: include{project_root}/includes/Psr/Log/LoggerInterface.php): ` But this is inside a Monolog, so now it founds Monolog. Thanks! – Daria Sep 29 '16 at 13:24
  • 1
    There is no need for `preg_replace()` here. `str_replace()` will do the job as well and is much faster. I would also recommend using `spl_autoload_register()` instead of `__autoload()`. – simon Sep 29 '16 at 13:26
  • 1
    While trying it I had the same error. It's because Monolog depends on Psr. See the composer.json from Monolog. You will need Psr. Or use composer to include Monolog and its dependencies, it will help a lot. – Thibault Sep 29 '16 at 13:27
  • @simon I switched to str_replace. Thanks. I let the OP decide wether she wants to use spl_autoload_register() or keep __autoload() – Thibault Sep 29 '16 at 13:40