Startup with class composer inside one file

I am trying to use a library that uses namespaces but has part of the code auto-generated, so they generate more than one class in one file.

We use a composer and I tried adding a namespace definition in psr-4, like this

"name\space\preffix\": "folder/where/the/file/is" 

But only one file containing all the classes inside startup does not find the classes, because, I think, it is looking for a file with the same name as the class you are trying to load. Is there a way to make composer autoloader aware of this situation and use autoload with classes?

+5
source share
2 answers

You have two more options besides PSR-4 (or PSR-0):

  • classmap - this scans directories or files for all classes that are contained, and the result is placed in a PHP array into a file. To do this, you must reset the autoloader whenever a scan file is modified.
  • files - these files will be included when you turn on the Composer autoloader.

So, you can either add a file with auto-generated classes, which will be checked using the classmap autoloader, which would load this file the first time ANY of the classes are used there, or you could add it to the autoload files, which will always be included, regardless whether classes are used or not.

If we consider performance, the first alternative is preferable if the number of classes is not large and the amount of code in the classes is small. Having a lot of tiny classes in classmap is probably more overhead than always, just loading them first.

Having a lot of code in these classes, and they are not always used, the amount or memory saved NOT always can be faster.

If in doubt: measure it. And consider splitting classes into separate files and using PSR-4 if this reduces performance too much.

+8
source

The PSR4 specification says:

The final class name matches the name of the file ending in .php. The file name MUST match the case of the trailing class name.

Because autogenerated code is not compatible with PSR4, it cannot be loaded automatically by the PSR4 autoloader. I would fix the code that generates classes, or use require_once .. (The first is preferable.

+1
source

Source: https://habr.com/ru/post/1200571/


All Articles