20160915

How to require autoload in vendor or outside vendor folder

Sometimes when you create a package for composer and want to create some example code you need to execute those examples as an standalone package or once included in a vendor folder of another project.

Use this simple trick in your example php files to require autoload in any location.

$autoload_location = '/vendor/autoload.php';
$tries=0;
while (!is_file(__DIR__.$autoload_location))
{
$autoload_location='/..'.$autoload_location;
$tries++;
if ($tries>10) die("Error trying to find autoload file\n");
}
require_once __DIR__.$autoload_location;



OLD VERSION:

$autoload_location=__DIR__.'/../vendor/autoload.php';
if (!is_file($autoload_location)) $autoload_location='../../../autoload.php';
require_once $autoload_location;