> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Processen

> Uitleg over het uitvoeren van externe shellcommando's met de Process-facade van Laravel en het beknopt afhandelen van synchrone, asynchrone en gelijktijdige verwerking.

## Inleiding

De Process-facade van Laravel is een dunne wrapper rond de [Symfony Process-component](https://symfony.com/doc/current/components/process.html).
Hij biedt een beknopte API om shellcommando's vanuit je Laravel-applicatie aan te roepen en de resultaten te verwerken.

```mermaid theme={null}
flowchart LR
    A["Laravel-app"] --> B["Process-<br>facade"]
    B --> C["Shellcommando"]
    C --> D["ProcessResult<br>(output / exitCode)"]
    D --> A
```

## Een proces starten

Met `Process::run()` voer je een commando synchroon uit en haal je het resultaat op.

```php theme={null}
use Illuminate\Support\Facades\Process;

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

return $result->output();
```

De `ProcessResult`-instantie biedt diverse methodes om het resultaat te inspecteren.

```php theme={null}
$result = Process::run('ls -la');

$result->command();       // Het uitgevoerde commando
$result->successful();    // Geslaagd (exitcode 0)
$result->failed();        // Mislukt (exitcode anders dan 0)
$result->output();        // Standaarduitvoer (stdout)
$result->errorOutput();   // Standaardfoutuitvoer (stderr)
$result->exitCode();      // Exitcode
```

### Een exception gooien bij falen

Om een `Illuminate\Process\Exceptions\ProcessFailedException` te laten gooien wanneer de exitcode groter is dan 0, gebruik je `throw()` of `throwIf()`.

```php theme={null}
$result = Process::run('ls -la')->throw();

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

## Procesopties

### Werkdirectory

Met `path()` geef je de werkdirectory op. Laat je die weg, dan wordt de werkdirectory van het huidige PHP-script gebruikt.

```php theme={null}
$result = Process::path(__DIR__)->run('ls -la');
```

### Standaardinvoer

Met `input()` geef je data door aan de standaardinvoer van het proces.

```php theme={null}
$result = Process::input('Hello World')->run('cat');
```

### Timeout

De standaard is 60 seconden. Met `timeout()` wijzig je die. Bij een timeout wordt het proces afgebroken en wordt een `ProcessTimedOutException` gegooid.

```php theme={null}
$result = Process::timeout(120)->run('bash import.sh');
```

Je kunt ook de `CarbonInterval`-helperfuncties gebruiken.

```php theme={null}
use function Illuminate\Support\minutes;

$result = Process::timeout(minutes(2))->run('bash import.sh');
```

Gebruik `forever()` om de timeout uit te schakelen.

```php theme={null}
$result = Process::forever()->run('bash import.sh');
```

Je kunt ook een idle-timeout instellen (het aantal seconden zonder uitvoer).

```php theme={null}
$result = Process::timeout(60)->idleTimeout(30)->run('bash import.sh');
```

### Omgevingsvariabelen

Met `env()` voeg je omgevingsvariabelen toe of overschrijf je ze. De omgevingsvariabelen van het systeem worden automatisch overgenomen.

```php theme={null}
$result = Process::forever()
    ->env(['IMPORT_PATH' => __DIR__])
    ->run('bash import.sh');
```

Om een overgenomen variabele uit te sluiten, geef je `false` op.

```php theme={null}
$result = Process::forever()
    ->env(['LOAD_PATH' => false])
    ->run('bash import.sh');
```

### Uitvoer uitschakelen

Heb je geen grote hoeveelheden uitvoer nodig, dan beperk je met `quietly()` het geheugengebruik.

```php theme={null}
$result = Process::quietly()->run('bash import.sh');
```

### Realtime uitvoer

Geef je een closure door als tweede argument van `run()`, dan ontvang je de uitvoer in realtime.

```php theme={null}
$result = Process::run('ls -la', function (string $type, string $output) {
    echo $output;
});
```

## Pipelines

Met `Process::pipe()` geef je de uitvoer van een commando door als invoer voor het volgende commando.

```php theme={null}
use Illuminate\Process\Pipe;
use Illuminate\Support\Facades\Process;

$result = Process::pipe(function (Pipe $pipe) {
    $pipe->command('cat example.txt');
    $pipe->command('grep -i "laravel"');
});

if ($result->successful()) {
    // ...
}
```

Je kunt ook een array van commandostrings doorgeven.

```php theme={null}
$result = Process::pipe([
    'cat example.txt',
    'grep -i "laravel"',
]);
```

Geef je elk proces met `as()` een sleutel, dan kun je in de uitvoerclosure bepalen van welk proces de uitvoer komt.

```php theme={null}
$result = Process::pipe(function (Pipe $pipe) {
    $pipe->as('first')->command('cat example.txt');
    $pipe->as('second')->command('grep -i "laravel"');
}, function (string $type, string $output, string $key) {
    // $key is 'first' of 'second'
});
```

## Asynchrone processen

Met `Process::start()` start je een proces asynchroon. Terwijl het proces draait, kan je applicatie andere taken blijven uitvoeren.

```php theme={null}
$process = Process::timeout(120)->start('bash import.sh');

while ($process->running()) {
    // Andere verwerking
}

$result = $process->wait();
```

### Proces-ID en signalen

Met `id()` haal je het OS-proces-ID van een lopend proces op.

```php theme={null}
$process = Process::start('bash import.sh');

return $process->id();
```

Met `signal()` stuur je een signaal naar het proces.

```php theme={null}
$process->signal(SIGUSR2);
```

### Uitvoer van asynchrone processen

Gebruik je tijdens de uitvoering `latestOutput()` en `latestErrorOutput()`, dan haal je de nieuwe uitvoer op sinds de vorige keer dat je die ophaalde.

```php theme={null}
$process = Process::timeout(120)->start('bash import.sh');

while ($process->running()) {
    echo $process->latestOutput();
    echo $process->latestErrorOutput();

    sleep(1);
}
```

Gebruik `waitUntil()` om te wachten tot bepaalde uitvoer verschijnt.

```php theme={null}
$process = Process::start('bash import.sh');

$process->waitUntil(function (string $type, string $output) {
    return $output === 'Ready...';
});
```

### Timeout controleren bij asynchrone processen

Roep je in de lus `ensureNotTimedOut()` aan, dan wordt een exception gegooid als het proces een timeout heeft bereikt.

```php theme={null}
$process = Process::timeout(120)->start('bash import.sh');

while ($process->running()) {
    $process->ensureNotTimedOut();

    sleep(1);
}
```

## Gelijktijdige processen

Met `Process::pool()` voer je meerdere processen gelijktijdig uit.

```php theme={null}
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) {
    // ...
});

while ($pool->running()->isNotEmpty()) {
    // ...
}

$results = $pool->wait();
```

Met `concurrently()` schrijf je het direct starten van een pool en het wachten op de resultaten in één regel.

```php theme={null}
[$first, $second, $third] = Process::concurrently(function (Pool $pool) {
    $pool->path(__DIR__)->command('ls -la');
    $pool->path(app_path())->command('ls -la');
    $pool->path(storage_path())->command('ls -la');
});

echo $first->output();
```

### Processen een naam geven

Geef je elk proces met `as()` een stringsleutel, dan wordt het ophalen van de resultaten duidelijker.

```php theme={null}
$pool = Process::pool(function (Pool $pool) {
    $pool->as('first')->command('bash import-1.sh');
    $pool->as('second')->command('bash import-2.sh');
    $pool->as('third')->command('bash import-3.sh');
})->start(function (string $type, string $output, string $key) {
    // ...
});

$results = $pool->wait();

return $results['first']->output();
```

Je kunt ook een signaal naar de hele pool sturen.

```php theme={null}
$pool->signal(SIGUSR2);
```

## Testen

### Processen faken

Met `Process::fake()` test je zonder daadwerkelijk shellcommando's uit te voeren.

```php theme={null}
use Illuminate\Support\Facades\Process;

Process::fake();

$response = $this->get('/import');

Process::assertRan('bash import.sh');
```

Je kunt ook uitvoer en exitcodes opgeven.

```php theme={null}
Process::fake([
    '*' => Process::result(
        output: 'Test output',
        errorOutput: 'Test error output',
        exitCode: 1,
    ),
]);
```

### Specifieke commando's faken

Met wildcards of commandostrings als sleutel kun je fakes per commando instellen.

```php theme={null}
Process::fake([
    'cat *'    => Process::result(output: 'file contents'),
    'ls -la'   => Process::result(output: 'file listing'),
]);
```

### Sequenties faken

Wanneer hetzelfde commando meerdere keren wordt aangeroepen, kun je de volgorde van de teruggegeven resultaten opgeven.

```php theme={null}
Process::fake([
    'ls *' => [
        Process::result('first time'),
        Process::result('second time'),
    ],
]);
```

### Assertions

| Methode                                 | Beschrijving                                                          |
| --------------------------------------- | --------------------------------------------------------------------- |
| `Process::assertRan('command')`         | Controleert dat het commando is uitgevoerd                            |
| `Process::assertNotRan('command')`      | Controleert dat het commando niet is uitgevoerd                       |
| `Process::assertRan(fn)`                | Controleert de uitvoering in detail met een closure                   |
| `Process::assertRanTimes('command', 3)` | Controleert dat het commando het opgegeven aantal keren is uitgevoerd |

### Onverwachte processen voorkomen

Roep je `Process::preventStrayProcesses()` aan, dan wordt een exception gegooid wanneer een commando wordt uitgevoerd waarvoor geen fake is ingesteld.

```php theme={null}
Process::preventStrayProcesses();

Process::fake([
    'ls *' => Process::result('file listing'),
]);

// Exception: voor 'bash import.sh' is geen fake ingesteld
Process::run('bash import.sh');
```

## Gerelateerde pagina's

<Columns cols={2}>
  <Card title="Artisan-console" icon="terminal" href="/nl/artisan">
    Maak eigen commando's en roep processen aan
  </Card>

  <Card title="Queues" icon="list" href="/nl/queues">
    Vergelijking met asynchrone verwerking
  </Card>
</Columns>


## Related topics

- [Artisan-console](/nl/artisan.md)
- [WebSocket (Jetstream / Firehose)](/nl/packages/laravel-bluesky/websocket.md)
- [Cache](/nl/cache.md)
- [Introductie testen](/nl/testing.md)
- [TCP-modus](/nl/packages/laravel-copilot-sdk/tcp-mode.md)
