Composer autoload classmap with key value for class name with non-matching filename

Viewed 325

Due to legacy I have a CMS with its own autoloader. Compsoser joined the party to manage some dependencies to ease payment integrations. However, I found the two autoloaders are conflicting with each other. Then I found I can use classmap in composer.json, but this doesn't seem to fix my issue - the requested class is not found.

For example I have a MySQL class, that resides in a file called Database.php. Using classmap so far I have been unable to properly load the MySQL class when I enter the filepath to Database.php in it. However, using the files container it works. But, if possible I want to prevent to brute force include all legacy classes for each page request.

I'm wondering if there's a possibility to define a key-value mapping for a classmap-like behavior. Thereby defining my composer.json something like:

{
   "require" : {
     "vendor/payment-service-provider-package": "version-data"
   },
   "autoload": {
     "classmap": [
       "MySQL" => "./CMS/Classes/Database.php",
       "..." => "./CMS/Classes/....php"
     ]
   }
}
1 Answers

You need only to declare the files that declare the classes, and the generated autoloader will create the necessary "key-value" mapping.

E.g. I have on lib/ a couple of files that declare classes will outside PSR-4:

  • FooBar.php that declares \Foo and \Bar.
  • FizzBuzz.php that declares \Extra\Fizz and \Extra\Buzz.

Also, within src/ I have the rest of the classes, following PSR-4 standards.

To include all these classes on autloading, I simply declare:

{
  "autoload": {
    "psr-4": {
      "App\\": "src"
    },
    "classmap": [
      "lib/"
    ]
  }
}

After running composer dump-autoload, composer will scan these directories and on vendor/composer/autoload_classmap.php I'll get:

<?php

// autoload_classmap.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Bar' => $baseDir . '/lib/FooBar.php',
    'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
    'Extra\\Buzz' => $baseDir . '/lib/FizzBuzz.php',
    'Extra\\Fizz' => $baseDir . '/lib/FizzBuzz.php',
    'Foo' => $baseDir . '/lib/FooBar.php',
);

... that includes all the necessary information to know which file it needs to read for each "not found" class.

Related