phplaravelcomposer-phpautoloadspl-autoload-register

Autoload files for PHP Package - get_declared_classes() not returning expected results


I have a package I am creating here

It's a standard composer PHP package with a Symfony command to generate Avro files.

When registering the package command in the bin/avro directory I add the following

require file_exists(__DIR__ . '/../vendor/autoload.php')
        ? __DIR__ . '/../vendor/autoload.php'
        : __DIR__ . '/../../../../vendor/autoload.php';

This should, if my understanding is correct, autoload all files for a project where the package is loaded in.

I run the following in an empty Laravel project for example

composer require lukecurtis93/avrogenerate
./vendor/bin/avro generate

The code here which uses get_declared_classes() - excerpt:

// ...
        $arr = [];
        foreach (get_declared_classes() as $className) {
            if (in_array(Avroable::class, class_implements($className))) {
                $arr[] = $className;
            }
        }
// ...

- does not return any files stored in my App/Models directory for example which are in the Laravel App (or any others for that matter).

What am I doing incorrectly? Shouldn't these files be available from get_declared_classes()? Is there additional configuration I need to do for a package?


Solution

  • Is there additional configuration I need to do for a package?

    IMSoP already explained the details for PHP autoload when you want to use get_declared_classes().

    An alternative to that is to re-use the Composer classmap, however it requires to generate it, the --optimize argument of composer dump-autoload does this. Given the Composer Autloader has been dumped that way, the list of "declared" classes is quite easy to obtain:

    $autoload = require file_exists(__DIR__ . '/../vendor/autoload.php')
            ? __DIR__ . '/../vendor/autoload.php'
            : __DIR__ . '/../../../../vendor/autoload.php';
    $classmap = $autoload->getClassMap();
    

    Then $classmap is an associative array with the class-names as key and the (absolute) path (w/ relative segments) to the file.

    This is with the downside that the autoloader must be dumped with a specific configuration. And with the benefit that you'd be ready in no time.

    Better Reflection

    The package roave/better-reflection provides a class-listing for composer.json and //vendor-dir/composer/installed.json without relying on the class-map of the Composer autoloader.

    You could add it as a requirement and then it would be available with the autoloader.

    Getting the list of classes is within their documentation1, it depends on the path to the project. You could make it an argument option for your utility as I don't know how to obtain the root project path from the autoloader instance, the following would assume the default vendor-dir configuration, YMMV:

    $projectAutoload = file_exists(__DIR__ . '/../vendor/autoload.php')
            ? __DIR__ . '/../vendor/autoload.php'
            : __DIR__ . '/../../../../vendor/autoload.php';
    $autload = require $projectAutoload;
    $projectRoot = dirname($projectAutload, 2);
    

    It does not implement 100% of the Composer autoloader configuration, but I've not seen another component that does apart from Composer itself. Just FYI when you wonder in integration testing, it is in the 99.5% camp, you may not even miss anything at all in your use-case.

    $astLocator = (new BetterReflection())->astLocator();
    $reflector  = new DefaultReflector(new AggregateSourceLocator([
        (new MakeLocatorForComposerJsonAndInstalledJson)($projectRoot, $astLocator),
        new PhpInternalSourceLocator($astLocator, new ReflectionSourceStubber())
    ]));
    
    $classes = $reflector->reflectAllClasses();
    $classNames = array_map(fn (ReflectionClass $rfl) => $rfl->getName(), $classes);
    

    Better Reflection also is not the fastest horse in the stable. Have decent CPU and fast disk I/O. The benefit of it are its features and in your specific case you can use it for preview (get_declared_classes() stays empty, no autoloading involved, you may use the gathered information to do your inheritance checks without loading the files into PHP - I can imagine this is probably good to have for your utility).

    Write it yourself

    It is relatively easy to write an ad-hoc loading of all PHP files in the vendor folder so that get_declared_classes() has them afterwards. But with such a direct implementation you can easily run into fatal errors, which don't help with your cause, also if you want to adhere to the composer packages, you need to give it some love. That depends also on which packages (and package style) you want to support. I've not much about a clue of your project, so in case you may still want to try it for yourself, some pointers:


    1. Compare "Inspecting code and dependencies of a composer-based project"