Search code examples
phpcomposer-php

Composer autoload definition for class with mismatching filename


I am trying to convert a legacy library class to using Composer.

However, currently the filename and class name are out of sync. While these need to be brought in sync as part of broader refactoring, that has knock-on effects and my objective at present is to migrate dependencies to Composer so that deployment can be modernised.

Currently the package is called myfoo, with the file at src/myFoo.php (which is consistent), but the class inside is inconsistently called foo. There are many external applications which call new foo, so the class name cannot at this point be easily changed, though that will happen in future (it needs namespacing etc., anyway, so that is the point to make that change).

Currently my autoload in composer.json is:

     "autoload": {
        "files": ["src/myFoo.php"]
     }

which I believe matches the documentation at https://getcomposer.org/doc/04-schema.md#files.

However, client code calls fail on new foo with Class "foo" not found.

What should the autoload definition be in this circumstance?


Solution

  • I'm not certain why the files directive wouldn't work in this case, however, if myFoo.php only declares the Foo class, you can use the classmap directive instead:

         "autoload": {
            "classmap": ["src/myFoo.php"]
         }