Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to get all classes when using autoloader

I'm using composer to generate autoloader:

"autoload": {
  "psr-4": {
    "SomeNamespace\\": "src/SomeDir"
  }
}

I need to create instances of all classes that implement specific interface. It's fairly easy when not using autoloader, however get_declared_classes() is not playing well with autoloaders. It will list a class only after it was instantiated with autoloader.

like image 272
SiliconMind Avatar asked Apr 17 '16 11:04

SiliconMind


People also ask

How does PHP autoloader works?

The PHP Autoloader searches recursively in defined directories for class, trait and interface definitions. Without any further configuration the directory in which the requiring file resides will be used as default class path. File names don't need to obey any convention. All files are searched for class definitions.

How autoload PHP class the composer way?

After you create the composer. json file in your project root with the above contents, you just need to run the composer dump-autoload command to create the necessary autoloader files. These will be created under the vendor directory. Finally, you need to include the require 'vendor/autoload.

What is the use of vendor autoload PHP?

In addition, the vendor/autoload. php file is automatically created. This file is used for autoloading libraries for the PHP project.

What is autoload file PHP?

What is autoloading? Every time you want to use a new class in your PHP project, first you need to include this class (using include or require language construct, that's right this are not functions). However if you have __autoload function defined, inclusion will handle itself.


1 Answers

You can use dirty hack and require_once all classes before get_declared_classes() function call.

  1. At first do dump all classes to class map via composer dumpautoload --optimize
  2. Now you can fetch composer loader and require all files
    $res = get_declared_classes();
    $autoloaderClassName = '';
    foreach ( $res as $className) {
        if (strpos($className, 'ComposerAutoloaderInit') === 0) {
            $autoloaderClassName = $className; // ComposerAutoloaderInit323a579f2019d15e328dd7fec58d8284 for me
            break;
        }
    }
    $classLoader = $autoloaderClassName::getLoader();
    foreach ($classLoader->getClassMap() as $path) {
        require_once $path;
    }
  1. Now you can easy use get_declared_classes() again, which return all classes the composer knowns

P.S. Don't use it in production.

like image 147
benbor Avatar answered Sep 24 '22 21:09

benbor