Reputation: 47
I'm trying to use the Composer autoloader located at vendor/autoload.php
. However, I can't seem to figure out how to get to the root of the project, from which I could then navigate to vendor/autoload.php
. I'm having to specify the relative path in each file (i.e. ../../../vendor/autoload.php
). This seems like a very nasty way to get to the autoloader, since this path will be different depending on how deep the file is.
Is there a way to get to the root directory without specifying a relative path, or do I need to go up x parent directories in every file?
Upvotes: 0
Views: 1122
Reputation: 97658
PHP has no way of knowing what the "root of the project" is. You could have any number of directories on your disk, with files called vendor/autoload.php
in several of them, and only you know what's special about the "project root". So ultimately, the answer is no, there is no way.
However, note that you only need to include the autoloader in files which aren't themselves included or autoloaded. The autoloader is something you load once, as part of the configuration / bootstrapping of your code, and it then loads whatever classes it needs wherever they're referenced.
So the way to limit the mess of different levels is to structure your project carefully. For instance:
The same principle applies to use in command-line scripts or any other kind of application: limit or structure the "entry points", because only those need to know where to load the autoloader.
If you already have some kind of config file loaded on every request / script run / unit test / etc, it might be sensible to put the require_once 'vendor/autoload.php';
line in there. Like the configuration, the autoloader is "global state" that you want to just set up once and then forget about.
Upvotes: 3