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.
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.
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.
In addition, the vendor/autoload. php file is automatically created. This file is used for autoloading libraries for the PHP project.
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.
You can use dirty hack and require_once
all classes before get_declared_classes()
function call.
composer dumpautoload --optimize
$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;
}
get_declared_classes()
again, which return all classes the composer knownsP.S. Don't use it in production.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With