How to define the path to autoload.php with composer
-
21-12-2019 - |
Question
I have a composer project, call it MyVendor\Database
. That project uses composer and autoloading. There are several files in that project that have:
require_once __DIR__."/../vendor/autoload.php";
in order to utilize autoloading.
It all works great, until I include MyVendor\Database
in another project.
I have another project, call it MyVendor\CoolPackage
that requires MyVendor\Database
.
I run composer install on CoolPackage
and it downloads MyVendor\Database
into the vendor folder.
The problem from here though, is My files within vendor\MyVendor\Database
fail because they call require_once __DIR__."/../vendor/autoload.php"
, but there is not vendor folder inside of \vendor\MyVendor\Database
.
Solution
In your composer.json
you define the autoloading scheme. For reasons you found out yourself now, it is not a good idea to call the Composer autoloading inside any of the files that are supposed to be autoloadable not only inside that application or module, but in any other application as well.
Basically, the files in any Composer project should be divided based on the definition of PSR-0 or 4 autoloading: They either ONLY do declaration of classes or functions WITHOUT any side effects (like executing code), or they execute code without defining classes or functions. Only the former files can be autoloaded (with the exception of functions, which would only be able to always be declared by loading the file containing them with a files
autoload section), the latter should NOT be autoloaded.
And then it should become relatively easy: All the classes that can be autoloaded can also be used when this component is included in another application. Anything else that is not a class cannot directly be used.