0
votes

I've added composer to an existing project that uses the PHP autoload function. Now that composer autoload.php is being used I've removed my old autoload function and I'm trying to load my existing source directory via composer autoload but it isn't picking up any of my existing source classes.

Everything installed by composer loads fine and can be accessed via namespaces etc. so it's just the existing sources in the source directory not being picked up. Any suggestions?

I've looked at a few other of the composer questions on stackoverflow but nothing I've read has solved my problem.

File structure:

 index.php
 root/
      sources/
      vendor/
      composer.json
 media/

Composer autoload:

 "autoload": {
    "psr-0": {
        "" : "sources/"
    }
 }
2
Where are your classes located, and what are they called? Are you following PSR-0 standards for path and filename layout?Sven
All source files are in the following format, 'classname.class.php', class name is the name used in the class.llanato
That's not PSR-0, so its normal that Composer cannot autoload it. Use "classmap" instead and be advised that you have to run composer dump-autoload every time you add a new class. Or rename the files to resemble the PSR-0 scheme (recommended).Sven
@Sven, I've updated the classes to have file names like 'Classname.php' but still not loading the classes.llanato
I'd need an example, one of your classnames and the complete path of it's file to compare them.Sven

2 Answers

2
votes

There were two things causing issues for me, one was the class file names and the second was a composer command that needed to be run.

My class file names were in the format {classname}.class.php when they need to be in the format that PSR-0 expects which is Classname.php (uppercase first letter) and in turn the classname in the class file follows the file name.

class Classname
{
    ...

The second issue was that I needed to run the below command.

composer dump-autoload

From composer.org:

If you need to update the autoloader because of new classes in a classmap package for example, you can use "dump-autoload" to do that without having to go through an install or update.

1
votes

If your code structure is too complex to convert to PSR-* structure, you can use your old autoloader and composer autoload together.

spl_autoload_register( function ( $class ) {
    $file = "sources/" . $class . ".class.php";
    if ( file_exists( $file ) ) {
        require $file;
        return;
    }
} );
require "vendor/autoload.php";