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
Related
I need to dump my autoloader every time I add a new class. I am using psr-4. I don't really know why I need to do so. In psr-4 it should automatically load the classes. Where am I going wrong?
Here's my composer.json file
{"autoload": {"psr-4": {"MyDomain\\": "app"}}}
Here's my directory structure:
Here's the code for one of my classes:
<?php
namespace MyDomain\Model;
class Employee {
}
?>
PSR-4 (and also PSR-0) requires that the class ClassName is stored in a file named ClassName.php. The names are case sensitive and they must match exactly.
The file names in your project are lowercase, the class names are mixed case. The default disk formats on Windows and macOS are case-insensitive on search. This means when a program searches for Employee.php and the file employee.php exists in the directory, the search succeeds and the OS returns the existing file even if the case of its name is not the same as the case of the required file. On Linux-based OSes, the default disk format is case sensitive and a program that searches for Employee.php cannot find employee.php.
Your composer.json file declares the app/ directory as the root directory of the MyDomain namespace that follows the PSR-4 standard. This is enough for the autoloader to find the file app/Models/Employee.php when it needs to load the class MyDomain\Models\Employee.
Because you run it on Ubuntu (which is a Linux-based OS), PHP cannot load the Employee.php file (because it doesn't exist) and the OS doesn't provide it the file employee.php instead.
It seems that you generate the autoloader using composer update -o or composer dump-autoload -o. The -o (short of --classmap-authoritative) tells Composer to scan the directories declared in composer.json (app/) in your case and create a classmap that contains all the classes it can find. A classmap is a list that maps the classnames (with the namespace) to filenames (with directories). This way, the autoloader knows exactly where to find each class and the loading goes faster.
The above two paragraphs explain why you need to regenerate the autoloader after you add a new class.
The correct way to do the job is to follow the PSR-4 requirements. To be more specific, each namespace under MyDomain must be stored in a subdirectory of app/ that has the same name, including the case. Each class must be stored in the correct subdirectory, in a file that has the same name as the class (including the case) and the termination .php (lowercase). For example, the class MyDomain\Models\Employee must stay in the file app/Models/Employee.php.
After you fix the file names you can run composer dump-autoload and forget about it. As long as the class and file names follow PSR-4 the autoloader will find them without regenerating it again.
On the production server you can run composer dump-autoload -o to improve its speed a little. Just don't forget to run it again after each deploy (or, even better, include the command in the deployment script).
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.
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 can't get my library to work. The directory structure is lib-name/src and inside theres a main dir and a tests dir, how do I tell composer to load from the /lib-name/src/main folder?
Link to my library github https://github.com/gerardorn/catalogo
There are 3 ways to map your classes for autloading with composer.
PSR-0
The recommended way is PSR-0 compatible. This protocol describes the directory structure of your library. Each namespace need to be a directory. Classes with underscores are separated as well (PEAR style).
In your case, the class Catalogable has a namespace gerardorn\catalogo. To be PSR-0 compatible the directory structure is:
- src
- main
- gerardorn
- catalogo
- Catalogable.php
In your composer.json you should put the following:
"autoload" : {
"psr-0" : {"gerardorn" : "src/main"}
}
Classmap
Alternatively you could use classmap. Classes are searched for in the directory regardless of the namespace.
"autoload": {
"classmap": ["src/main"]
}
Files
The 3th method files doesn't apply in your case.
PHPUnit
Note that PHPUnit is needed to test your library, but not to run your library. Therefor you shouldn't put that up as a required library.
It's good that you're writing unit tests. You should sign up for Travis CI. It will run your PHPUnit tests each time that you push to GitHub and warn you (by e-mail) if something got broken.
Your directory structure should be PSR-0 compatible.
i.e. your file Catalogable.php has a namespace gerardorn\catalogo, so your directory structure for this has to match the following.
- src
- main
- gerardorn
- catalogo