I have a problem with composer auto loader. Currently working on a application which was developed about 10 years back. The folder structure of 2 libraries which are currently used in the project do not comply the psr0 and psr4 auto loading rules.
The structure after the composer install looks as follows
Example 1
Folder path: /vendor/AppBook/ORS/class/model/Country
Filename: class.Country.php
PHP Class name: Country
Example 2
Folder path: /vendor/AppBook/ORS/class/model/Country
Filename: class.CountryCollection.php
PHP Class name: CountryCollection
Please advise what should I do in order that composer auto loader can detect these files.
Thank you in advance
From the docs:
You can use the classmap generation support to define autoloading for all libraries that do not follow PSR-0/4. To configure this you specify all directories or files to search for classes.
Example:
{
"autoload": {
"classmap": ["src/", "lib/", "Something.php"]
}
}
You can still add composer.json to your legacy libraries and define classmap autoloading type for them.
You can rename these files to make them compatible to PSR-4 (unlikely because that requires using namespaces - in 10 years old code?) or PSR-0. Additionally, you have to remove any explicit loading of these files via include, include_once, require or require_once because the file names changed.
PHP will autoload these classes by their class name. This will possibly run into issues if the case sensitivity in the class name is not respected everywhere. Example:
class UpperCase {}
$a = new upperCase();
The autoloading would try to find a file ending with upperCase.php, which will not match the PSR-0 required UpperCase.php, so the code will fail. However, this will work, making the situation not better:
class UpperCase {}
$b = new UpperCase();
$a = new upperCase();
The reason is that PHP treats class names case insensitive, so once a class is loaded, you can use any case in it's name. It is only the first occurrence in your code path that has to match. The problem is to be sure where this really is, so essentially it has to be correct everywhere.
Yes, the classmap feature is the easier way. But you'd still want to remove include/require calls to optimize the performance a bit, so you have to touch the code anyway. And despite it's age, it has to be maintained - so why not do it fully, switching to a well-known autoloading standard. It will help you in the long run when you have to maintain PSR-0/4 compatible classes and this old code in parallel.
Related
I just upgraded to Composer 2.0 which has apparently made some modifications to how it parses classes...
composer dump-autoload -o or the alias composer du -o basically dumps a lot of lines in my console with text like:
Class MyProject\SubCategory\CoolClass located in C:/udvikling/MyProjectRoot/src/MyProjectClasses\MyProject\SubCategory\CoolClass.php does not comply with psr-4 autoloading standard. Skipping
After reading Composer psr-4 autoload issue i ensured that all names that contribute to my namespaces and classpaths are capitalized. i.e. use myproject/helperclass is now use MyProject/HelperClass
My C:/udvikling/MyProjectRoot/src/composer.json includes the following
"autoload": {
"psr-4": {
"MyProject\\": "MyProjectClasses/"
}
}
I made one go away by adding a leading backslash to the classname:
<?php
namespace \MyProject\Core;
class Timer {
//...
but... according to php.net
Fully qualified names (i.e. names starting with a backslash) are not allowed in namespace declarations, because such constructs are interpreted as relative namespace expressions.
So this seems to not be the right choice... (my IDE also gave me an angry squiggly line under it...)
Besides going back to another version of composer, how do I fix this?
File structure:
C:\udvikling\MyProjectRoot -- the root of the project
C:\udvikling\MyProjectRoot\src --the php sources
C:\udvikling\MyProjectRoot\src\MyProjectClasses -- my PHP classes
C:\udvikling\MyProjectRoot\src\vendor -- my vendor stuff for composer
C:\udvikling\MyProjectRoot\src\composer.json - my composer config
I went and did some extra reading.
Apparently one of the goals of psr-4 is to reduce the folder depth.
The “src” and “tests” directories have to include vendor and package directory names. >This is an artifact of PSR-0 compliance.
Many find this structure to be deeper and more repetitive than necessary. This proposal suggests that an additional or superseding PSR would be useful [...]
It’s difficult to implement package-oriented autoloading via an extension or amendment to PSR-0, because PSR-0 does not allow for an intercessory path between any portions of the class name.
So basically, the issue was that inside my MyProjectClasses directory, for the class MyProject\Core\Timer I had it in a similar directory structure:
C:\udvikling\MyProjectRoot\src\MyProjectClasses\MyProject\Core\Timer.php.
This had to be altered to that the base package was not included: C:\udvikling\MyProjectRoot\src\MyProjectClasses\Core\Timer.php
I've added the following to my composer.json file. This works fine but I have a long list of sub-namespaces (eg. Apple, Orange, Lemon, Pear, Banana... etc) that I want to include.
1) Do I have to indicate each sub-namespace or is there a shortcut eg. "Pure\\*": "pure"
composer.json:
"autoload": {
"psr-4": {
"Pure\\": "pure",
"Pure\\Apple\\": "pure/src/Pure/Apple",
"Pure\\Orange\\": "pure/src/Pure/Orange",
"Pure\\Lemon\\": "pure/src/Pure/Lemon"
}
}
2) Is it better to include a custom autoload file instead:
composer.json:
"autoload": {
"files": [
"pure/src/Pure/autoload.php"
]
}
autoload.php:
spl_autoload_register(function ($class) {
//etc...
}
Do I have to indicate each sub-namespace or is there a shortcut
When declaring the autoloading, you should use the longest possible or reasonable prefix.
If this example package is the only one you are ever creating, and it is the only one using Pure as the namespace, go with that if the number of longer prefixes in several subdirectories is too high. However, this assumes that any other package in the world that you are using should avoid doing the same thing with the same namespace.
Composer will be able to search for sub namespaces in all available directories, i.e. if you have two packages, and one says Pure is to be found in pure/src/Pure, and the other says Pure is in code/stuff, Composer will try to find a class Pure\Something\Class in one of these directories first, then has to try the second one if it does not find it. Composer will remember whether the pure/src/Pure/Something directory exists and avoid looking for anything starting with Pure\Something there if a second class in that namespace has to be loaded.
But from a code organization standpoint, one package should only ever provide a defined set of namespaces, and no other package should provide classes in the same namespace. You could accidentially add the same class into two packages and get interesting problems that may be hard to debug if the two files are different.
Is it better to include a custom autoload file instead:
No, avoid it at all cost. You won't get any benefit from this because the file always has to be loaded, and it is duplicate code that occupies some memory - you already have the autoloader from Composer. If you have code that does not conform to PSR-4 or PSR-0, you can use a classmap. For new code: Use PSR-4 only!
Also, your custom autoloader cannot be optimized by Composer. Although any optimization should be measured for effectiveness (read my detailed answer on this: Why use a PSR-0 or PSR-4 autoload in composer if classmap is actually faster?), using your own autoloader will entirely prevent your code from being optimized if it would be beneficial.
I've added the following to my composer.json file. This works fine but I have a long list of sub-namespaces (eg. Apple, Orange, Lemon, Pear, Banana... etc) that I want to include.
1) Do I have to indicate each sub-namespace or is there a shortcut eg. "Pure\\*": "pure"
composer.json:
"autoload": {
"psr-4": {
"Pure\\": "pure",
"Pure\\Apple\\": "pure/src/Pure/Apple",
"Pure\\Orange\\": "pure/src/Pure/Orange",
"Pure\\Lemon\\": "pure/src/Pure/Lemon"
}
}
2) Is it better to include a custom autoload file instead:
composer.json:
"autoload": {
"files": [
"pure/src/Pure/autoload.php"
]
}
autoload.php:
spl_autoload_register(function ($class) {
//etc...
}
Do I have to indicate each sub-namespace or is there a shortcut
When declaring the autoloading, you should use the longest possible or reasonable prefix.
If this example package is the only one you are ever creating, and it is the only one using Pure as the namespace, go with that if the number of longer prefixes in several subdirectories is too high. However, this assumes that any other package in the world that you are using should avoid doing the same thing with the same namespace.
Composer will be able to search for sub namespaces in all available directories, i.e. if you have two packages, and one says Pure is to be found in pure/src/Pure, and the other says Pure is in code/stuff, Composer will try to find a class Pure\Something\Class in one of these directories first, then has to try the second one if it does not find it. Composer will remember whether the pure/src/Pure/Something directory exists and avoid looking for anything starting with Pure\Something there if a second class in that namespace has to be loaded.
But from a code organization standpoint, one package should only ever provide a defined set of namespaces, and no other package should provide classes in the same namespace. You could accidentially add the same class into two packages and get interesting problems that may be hard to debug if the two files are different.
Is it better to include a custom autoload file instead:
No, avoid it at all cost. You won't get any benefit from this because the file always has to be loaded, and it is duplicate code that occupies some memory - you already have the autoloader from Composer. If you have code that does not conform to PSR-4 or PSR-0, you can use a classmap. For new code: Use PSR-4 only!
Also, your custom autoloader cannot be optimized by Composer. Although any optimization should be measured for effectiveness (read my detailed answer on this: Why use a PSR-0 or PSR-4 autoload in composer if classmap is actually faster?), using your own autoloader will entirely prevent your code from being optimized if it would be beneficial.
I have created a very basic validator class.
My base code is in a my src/ folder, which gets autoloader with
"kevdotbadger\\Validator\\": "src/"
this works fine, so that when I instantiate a new "kevdotbadger\Validator\ Validator is gives me src/Validator.php
My Validator.php class then loads a bunch of sub-classes in my src/Rules directory. These are magically loaded by using the __call, so ->between() should look for src/Rules/between.php. However, for some reason it won't usual load despite it being setup in my composer.json file.
My whole codebase is available at https://github.com/kevdotbadger/validator/
Have I setup my namespace correctly? I think the problem might be with php version 5.3, however I need to use version 5.3.
Thanks.
Well you need to keep the guidelines of psr-4 as you are using it to autoload.
change the folder name "rules" to "Rules"
Uppercase all your file names of classes like:
between.php --> Between.php
that should do the job
I am currently running Slim and Twig, my folder structure is as follow
/application/modules
In my composer.json I have
"autoload": {
"psr-4": {
"Application\\": "application/modules/",
"Core\\": "application/",
"Middleware\\": "application/slim/middleware/"
}
}
My issue is is that in Application\modules\ I have a directory for each module. Now my question is, is it possible to make composer iterate through the sub directories when using PSR-4 autoload?
I see an issue with your PSR-4 declaration.
You shouldn't place "Core" classes inside a folder that has subfolders for other namespaces.
PSR-4 autoloading in Composer works like this: If the fully qualified class name of the class to load matches a prefix declared in any of the PSR-4 definitions, then the prefix mentioned in the prefix is removed from the class name, and the remaining class name is mapped to a filename and being searched.
If you have classes named Application\ in the folder application/modules, and you have classes named Core\ in the folder application, then technically Composer might find files that match a class name like Core\modules\Whatever, although these file will contain a class Application\Whatever instead.
I recommend moving all the Core classes into their own folder and point to this in the PSR-4 declaration.
The problem with your original question is that you omit an important information: What is the class and file structure for your modules?
Composer's autoloader will happily resolve any class that starts with the namespace prefix Application, remove that prefix from the classname, convert the remainders into a path name and search for that file in application/modules/. Given that you have a module class Application\MyModule\Foobar, it will be searched in application/modules/MyModule/Foobar.php. Why? Because the prefix Application will be removed to allow for shorter path names in PSR-4. (Using PSR-0 would mean you have to have a folder for every level of namespace in the classname.)
Note that it is recommended for optimum performance to make the prefix for namespaces as long as possible, because Composer allows to have more than one directory for any given prefix, but then has to search for the correct file in more than one directory. Searching for files is time consuming!