Welcome, I hope my blog is of some use for you!


Using composer from code with symphony

Composer is a great dependency manager. But what if you want run composer from your application? For instance you’re a creating a new class from code, but can’t call that class yet because you have not run composer dumpautoload yet.

In an automated system it’s inconvenient to run composer dumpautoload manually so we have want to run it from code.


For this we can use symphony. Symphony has a process class. This class can run commands in a sub-process and by-passes the need for shell_exec functions. To install symphony process class run:

composer require symfony/process

Now we are able to run commands.
But we wanted to run composer from code, how do we handle that?
Because we can’t be certain composer is installed on the server we need find another way.

For this I have written a helper class that does this for you. This class will check for a composer.phar file and if that file does not exists, it downloads from the composer site.

Two methods in here really matter, dumpautoload and run. The method dumpautoload is just a shortcut for running composer dumpautoload. With the run command you can run any other command for composer.

use Symfony\Component\Process\Process;

class Composer
private $process;

public function __construct()
$this->process = new Process(null);

public function run($command, $callback = null)
$this->process->setCommandLine('php composer.phar ' . $command);
return $this->process->run($callback);

public function vendorPath()
$object = json_encode(file_get_contents(base_path('composer.json')));
return $object->config->{'vendor-dir'} ?? base_path('vendor');

public function dumpautoload($callback)
return $this->run('dumpautoload -o', $callback);

public function checkComposerFile()
return !file_exists(base_path('composer.phar'));

public function downloadComposerPhar()
if ($this->checkComposerFile()) {
copy('https://getcomposer.org/composer.phar', base_path('composer.phar'));

Sign up for our Newsletter and
stay informed

Leave a Reply

Your email address will not be published. Required fields are marked *