Last Updated: February 25, 2016
·
638
· wkjagt

Excecutables in Composer

Adding command line executables to composer while keeping all autoload functionality is easy. Taking imagine_cli as an example, you would have an executable file bin/imagine_cli in your project. Adding

"bin": ["bin/imagine_cli"]

at the root of your composer.json will instruct composer to create a symlink vendor/bin/imagine_cli that links to that executable when your project is included as a dependency of another project.

To keep autoloading work in case you use your project stand-alone, and when included in another project, use something similar to this in your executable file (copied from phpunit):

$files = array(
  __DIR__ . '/../vendor/autoload.php', // when in main projects
  __DIR__ . '/../../../autoload.php', // when executed as dependency
);

$found = FALSE;

foreach ($files as $file) {
    if (file_exists($file)) {
        require $file;

        $found = TRUE;

        break;
    }
}

if (!$found) {
    die('autoloader not found');
}

// your executable code here

Now running your executable from a project is as simple as

vendor/bin/imagine_cli