I’m trying to use a library that uses namespaces but has a part of the code auto-generated so they generate more than one class in a single file.
We use composer and I tried to add the namespace define in psr-4 like this
But there’s only one file that contains all the classes inside the autoload doesn’t find the classes as, I imagine, it searches a file with the same name as the class you are trying to load. Is there a way to make composer autoload aware of this situation and use autoload with the classes ?
You have two other options besides PSR-4 (or PSR-0):
classmap– this will scan directories or files for all classes that are contained, and the result is put into a PHP array in a file. This requires to dump the autoloader whenever there is a change being made to the files being scanned.
files– the mentioned file(s) will be included whenever the Composer autoloader is included.
So you could either add the file with the autogenerated classes to be scanned with the classmap autoloader, which would load that file on the first usage of ANY of the classes in there, or you could add it to the files autoloading, which will always be included, no matter if the classes are being used or not.
If considering performance, the first alternative is preferred unless the amount of classes is huge and the amount of code in the classes is tiny. Having plenty of tiny classes in a classmap probably is more overhead than always just loading them in the first place.
Having plenty of code in these classes, and they are not always used, the amount or memory saved by NOT always loading them might be faster.
If in doubt: Measure it. And consider to split the classes into single files and use PSR-4 if it is too much of a performance penalty.
The PSR4 spec says:
The terminating class name corresponds to a file name ending in .php. The file name MUST match the case of the terminating class name.
Since the autogenerated code isn’t PSR4 compatible, it can’t get autoloaded by a PSR4 autoloader. I would fix the code which generates the classes or, use
require_once.. (The first is preferered.