I talk about code and stuff
If you’re building a command line application you want to distribute with Composer, like I just did with cpx, what path do you require to get the Composer autoloader so your code works?
It might seem like a simple question, but depending on where your CLI is being run from, the path to the autoloader will be different:
vendor/autoload.php
vendor/<vendor>/<package>
directory of a project, you probably want to require ../../autoload.php
vendor/bin
directory of a project, Composer will set a variable in $GLOBALS['_composer_autoload_path']
that you can useTaking all of this into account, here’s the code I use in cpx
to detect the autoloader so it’ll work in all scenarios:
if (isset($GLOBALS['_composer_autoload_path'])) {
require_once $GLOBALS['_composer_autoload_path'];
unset($GLOBALS['_composer_autoload_path']);
} else {
foreach ([__DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php'] as $file) {
if (file_exists($file)) {
require_once $file;
break;
}
}
unset($file);
}