Symfony 2 Process Component

About me

  • Vo Xuan tien
  • PHP/Drupal developer
  • Go1

Outline

  • Definition
  • Use cases
  • Demo
  • References

What?

The Process component executes commands in sub-processes.

What is sub-process?

New process, is not related to the main process.

Process vs Console

  • Console: Allow to create command-line commands
  • Process: Allow to execute command-line commands

Use cases

  • Test your app's command
  • Insulate web test cases
  • Run compressors using assetic
  • Download and install libraries using composer

Demo

  • Basic usage
  • Asynchronous
  • Time out
  • Idle time out
  • Process builder
  • PHP Process

Basic

use Symfony\Component\Process\Process;

$process = new Process('ls -lsa');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new \RuntimeException($process->getErrorOutput());
}

echo $process->getOutput();

Asynchronous

require_once dirname(__FILE__) . '/../vendor/autoload.php';

use Symfony\Component\Process\Process;

$process = new Process('php ' . __DIR__ . '/data/sub_process.php');
$process->start();

while ($process->isRunning()) {
  sleep(1);
  echo "In main process\n";
  echo $process->getIncrementalOutput();
}

// Print full output so far.
// echo $process->getOutput();

Time out - Main process

require_once dirname(__FILE__) . '/../vendor/autoload.php';

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessTimedOutException;

$process = new Process('php ' . __DIR__ . '/helper/timeout.php');
$process->setTimeout(2);
// $process->setIdleTimeout(2);
$process->start();

try {
    $process->wait(function ($type, $buffer) {
        if (Process::ERR === $type) {
            echo 'ERR > '.$buffer;
        } else {
            echo 'OUT > '.$buffer;
        }
    });
} catch (ProcessTimedOutException $e) {
    echo "Time out\n";
}

Time out - Sub process

echo "Doing job in sub-process. This will take 3 seconds.\n";

for ($i = 0; $i < 3; $i++) {
  sleep(1);
  echo "Still in sub-process, " . (2 - $i)  . " seconds remaining!\n";
}

echo "Job in sub-process is done!\n";

Idle time out - Sub process

sleep(3);

print "Job in sub-process is done!\n";

Process builder

$builder = new ProcessBuilder();
$builder->setPrefix('/bin/tar');

// Building command: '/bin/tar cfvz backup.tar.gz data/'
$command = $builder
    ->setArguments(array('cfvz', 'backup/backup.tar.gz', 'data/'))
    ->getProcess()
    ->getCommandLine();

echo "You can run this command manually: $command\n";

$process = new Process($command);
$process->run();

References

process

By Tiến Võ Xuân