I'm on a Laravel project using new-ish versions of PHP, Laravel and Composer 2, as of this writing. I added a new app/Traits/MyTrait.php
file beside several existing trait files but unfortunately Composer absolutely will not detect the new file. I'm getting this error:
Trait 'App\Traits\MyTrait' not found
Similar to:
Laravel Custom Trait Not Found
Here is the general layout of the code:
# app/Traits/MyTrait.php:
<?php
namespace App\Traits;
trait MyTrait {
// ...
}
# app/Notifications/MyBaseClass.php:
<?php
namespace App\Notifications;
use App\Traits\MyTrait;
class MyBaseClass
{
use MyTrait;
// ...
}
# app/Notifications/MyChildClass.php
<?php
namespace App\Notifications;
class MyChildClass extends MyBaseClass
{
// ...
}
The weird thing is that this code runs fine in my local dev, but no matter what I try, it won't work when deployed to the server while running in a Docker container. I've tried everything I can think of like saving "optimize-autoloader": true
in composer.json
and running composer dump-autoload -o
during deployment, but nothing fixes it:
https://getcomposer.org/doc/articles/autoloader-optimization.md
I'm concerned that this inheritance permutation may not have been tested properly by Composer or Laravel, so this may be a bug in the tools. If worse comes to worse, I'll try these (potentially destructive) workarounds:
- Calling
composer dump-autoload -o
(greatly slows deployment, as this is a large project, and so far doesn't seem to fix it anyway) - Deleting via
rm vendor/composer/autoload_classmap.php
,rm vendor/composer/autoload_psr4.php
and/orrm vendor/composer/autoload_namespaces.php
(or similar) in thevendor
folder before each deployment to force Composer to rebuild. - Deleting via
rm -rf vendor
The sinister part about this is that we must have full confidence in our deploy process. We can't hack this in our server dev environments by manually deleting stuff like vendor
and then have it fail in the production deploy because Composer tripped over stale data in its vendor
folder. My gut feeling is that this is exactly what's happening, perhaps due to an upgrade from Composer 1 to Composer 2 or version change or stale cache files from work in recent months.
Even a verification like "this minimal sample project deployed to Docker works for us" would help to narrow this down thanks.
Edit: this is a useful resource on how the Composer autoloader works: https://jinoantony.com/blog/how-composer-autoloads-php-files