Search code examples
phpcomposer-phpautoloader

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.


Solution

  • If you don't keep track of which classes exist, autoloading won't help you.

    But the situation would be pretty much the same if you tried to include all files and see which classes would come out of it, when there would be a chance that you missed a file.

    Whatever it is what you try to do: Try it differently. I highly doubt you have to instantiate ALL these classes when serving one single request. It would not be very beneficial to the performance if you had to scan ALL declared classes for an interface, and then create an instance for all of them.

    Provide some kind of registering method to let the application know about your classes. If you really have to use them all, so be it. But scanning whatever code has been run previously does not sound right (and you didn't explain what you do at all).