Skip to content

Processes ​

Giới thiệu (Introduction) ​

Laravel cung cấp API tối giản quanh Symfony Process component để chạy external processes (lệnh shell) từ ứng dụng.

Chạy Processes (Invoking Processes) ​

php
use Illuminate\Support\Facades\Process;

$result = Process::run('ls -la');

$result->successful();      // bool
$result->failed();          // bool
$result->exitCode();        // int
$result->output();          // stdout
$result->errorOutput();     // stderr

Tùy chọn ​

php
$result = Process::path(__DIR__)
    ->timeout(120)
    ->env(['APP_ENV' => 'production'])
    ->run('ls -la');

Input ​

php
$result = Process::input('Hello World')->run('cat');

Throw on Failure ​

php
$result = Process::run('ls -la')->throw();
$result = Process::run('ls -la')->throwIf($condition);

Async Processes ​

php
$process = Process::start('bash import.sh');

while ($process->running()) {
    // Xử lý khác...
}

$result = $process->wait();

Process Output Streaming ​

php
$process = Process::start('bash import.sh', function (string $type, string $output) {
    echo $output;
});

$result = $process->wait();

Signals ​

php
$process->signal(SIGTERM);

Concurrent Processes (Process Pools) ​

php
use Illuminate\Process\Pool;
use Illuminate\Support\Facades\Process;

$pool = Process::pool(function (Pool $pool) {
    $pool->path(__DIR__)->command('bash import-1.sh');
    $pool->path(__DIR__)->command('bash import-2.sh');
    $pool->path(__DIR__)->command('bash import-3.sh');
})->start(function (string $type, string $output, int $key) {
    // Output callback...
});

$results = $pool->wait();

$results[0]->successful();
$results[1]->output();

Named Pools ​

php
$pool = Process::pool(function (Pool $pool) {
    $pool->as('first')->command('bash import-1.sh');
    $pool->as('second')->command('bash import-2.sh');
})->start();

$results = $pool->wait();

$results['first']->successful();

Testing ​

Fake Processes ​

php
use Illuminate\Support\Facades\Process;

Process::fake();

// Action...

Process::assertRan('ls');
Process::assertRan(function (PendingProcess $process, ProcessResult $result) {
    return $process->command === 'ls';
});
Process::assertNotRan('rm -rf');

Fake với Output tùy chỉnh ​

php
Process::fake([
    'ls *' => Process::result(
        output: 'file1.txt file2.txt',
        exitCode: 0,
    ),
    '*' => Process::result(exitCode: 1),
]);

Fake Sequences ​

php
Process::fake([
    'ls' => Process::sequence()
        ->push(Process::result(output: 'first'))
        ->push(Process::result(output: 'second')),
]);