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

# Laravel Octane

> Velocizza le applicazioni Laravel con FrankenPHP, Swoole o RoadRunner

## Cos'è Octane

[Laravel Octane](https://github.com/laravel/octane) è un pacchetto che migliora drasticamente le prestazioni di Laravel usando application server ad alte prestazioni.

Con PHP-FPM l'app parte e termina a ogni richiesta. Con Octane l'app parte una volta e resta in memoria: le richieste successive sono molto più veloci.

```mermaid theme={null}
sequenceDiagram
    participant Client
    participant Nginx
    participant Octane as Octane<br>(processo residente)
    participant App as App Laravel
    Client->>Nginx: Richiesta
    Nginx->>Octane: Proxy
    Octane->>App: Elabora in memoria
    App->>Nginx: Response
    Nginx->>Client: Response
```

La differenza principale con PHP-FPM: il bootstrap (service provider, ecc.) non si ripete per ogni richiesta.

## Server supportati

```mermaid theme={null}
flowchart LR
    A["Scelta server"] --> B{"Task concorrenti o<br>funzioni Swoole?"}
    B -->|"Sì"| C["Swoole<br>(estensione PECL)"]
    B -->|"No"| D{"HTTP/3, Brotli?"}
    D -->|"Sì"| E["FrankenPHP<br>(consigliato)"]
    D -->|"No"| F["RoadRunner<br>(binario Go)"]
```

| Server     | Linguaggio     | Installazione    | Task concorrenti | Note                           |
| ---------- | -------------- | ---------------- | ---------------- | ------------------------------ |
| FrankenPHP | Go             | Automatica       | —                | Consigliato. HTTP/3, Brotli    |
| RoadRunner | Go             | Automatica       | —                | Semplice                       |
| Swoole     | Estensione PHP | Manuale via PECL | ✅                | Task concorrenti, Octane cache |

<Info>
  Laravel Cloud offre Octane con FrankenPHP completamente gestito.
</Info>

## Installazione

```bash theme={null}
composer require laravel/octane
```

```bash theme={null}
php artisan octane:install
```

Il prompt ti fa scegliere il server; viene creato `config/octane.php`.

### FrankenPHP / RoadRunner

Octane scarica il binario. Nessun passo aggiuntivo.

### Swoole

```bash theme={null}
pecl install swoole
```

Per Open Swoole:

```bash theme={null}
pecl install openswoole
```

## Avvio

```bash theme={null}
php artisan octane:start
```

Porta di default `8000`.

```bash theme={null}
php artisan octane:start --server=frankenphp
php artisan octane:start --server=roadrunner
php artisan octane:start --server=swoole
```

### Worker

```bash theme={null}
php artisan octane:start --workers=4
```

Con Swoole e task worker:

```bash theme={null}
php artisan octane:start --workers=4 --task-workers=6
```

### Watch file

```bash theme={null}
php artisan octane:start --watch
```

<Warning>
  Serve [Node.js](https://nodejs.org) e Chokidar.

  ```bash theme={null}
  npm install --save-dev chokidar
  ```
</Warning>

### Comandi

```bash theme={null}
php artisan octane:reload
php artisan octane:stop
php artisan octane:status
```

## Attenzioni con la DI

Il codice resta in memoria: `register`/`boot` dei service provider vengono eseguiti una sola volta all'avvio.

```mermaid theme={null}
flowchart LR
    A["Avvio server<br>(una volta)"] --> B["ServiceProvider<br>register / boot"]
    B --> C["Istanza applicazione<br>in memoria"]
    C --> D["Richiesta 1"]
    C --> E["Richiesta 2"]
    C --> F["Richiesta 3..."]
```

### Iniezione del container

```php theme={null}
// ❌ Il container "vecchio" viene riusato
$this->app->singleton(Service::class, function (Application $app) {
    return new Service($app);
});

// ✅ Chiuso in closure per prendere sempre l'ultimo
$this->app->singleton(Service::class, function () {
    return new Service(fn () => Container::getInstance());
});
```

L'helper globale `app()` e `Container::getInstance()` restituiscono sempre l'ultimo container.

### Iniezione della request

```php theme={null}
// ❌
$this->app->singleton(Service::class, function (Application $app) {
    return new Service($app['request']);
});

// ✅ Closure
$this->app->singleton(Service::class, function (Application $app) {
    return new Service(fn () => $app['request']);
});

// ✅ Migliore: passa solo il valore necessario al metodo
$service->method($request->input('name'));
```

<Info>
  I type hint di `Illuminate\Http\Request` nei metodi controller/route sono sicuri. `request()` restituisce sempre la richiesta corrente.
</Info>

### Iniezione del config repository

```php theme={null}
// ❌
$this->app->singleton(Service::class, function (Application $app) {
    return new Service($app->make('config'));
});

// ✅
$this->app->singleton(Service::class, function () {
    return new Service(fn () => Container::getInstance()->make('config'));
});
```

L'helper `config()` restituisce sempre l'ultimo.

## Memory leak

Attenzione a static che accumulano dati:

```php theme={null}
// ❌ Cresce a ogni richiesta
class Service
{
    public static array $data = [];
}

public function index(Request $request): array
{
    Service::$data[] = Str::random(10);
    return [];
}
```

### max-requests

Riavvia i worker dopo N richieste (default 500):

```bash theme={null}
php artisan octane:start --max-requests=250
```

### Tempo massimo di esecuzione

In `config/octane.php` (default 30s):

```php theme={null}
'max_execution_time' => 30,
```

<Warning>
  Riavvia Octane dopo modifiche.
</Warning>

## Task concorrenti (solo Swoole)

```php theme={null}
use App\Models\User;
use App\Models\Server;
use Laravel\Octane\Facades\Octane;

[$users, $servers] = Octane::concurrently([
    fn () => User::all(),
    fn () => Server::all(),
]);
```

Task worker con `--task-workers`.

```bash theme={null}
php artisan octane:start --workers=4 --task-workers=6
```

<Warning>
  Max 1024 task per chiamata (limite Swoole).
</Warning>

## Tick e Interval (solo Swoole)

```php theme={null}
use Laravel\Octane\Facades\Octane;

Octane::tick('delayed-ticker', fn () => ray('Ticking...'))
    ->seconds(10);

Octane::tick('immediate-ticker', fn () => ray('Ticking...'))
    ->seconds(10)
    ->immediate();
```

## Octane cache (solo Swoole)

Fino a 2 milioni di ops/s.

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

Cache::store('octane')->put('framework', 'Laravel', 30);
```

### Interval cache

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

Cache::store('octane')->interval('random', function () {
    return Str::random(10);
}, seconds: 5);
```

<Warning>
  I dati si perdono al riavvio.
</Warning>

## Tabelle Swoole (solo Swoole)

In `config/octane.php` sezione `tables`:

```php theme={null}
'tables' => [
    'example:1000' => [
        'name' => 'string:1000',
        'votes' => 'int',
    ],
],
```

```php theme={null}
use Laravel\Octane\Facades\Octane;

Octane::table('example')->set('uuid', [
    'name' => 'Nuno Maduro',
    'votes' => 1000,
]);

$row = Octane::table('example')->get('uuid');
```

<Warning>
  Tipi supportati: `string`, `int`, `float`. I dati si perdono al riavvio.
</Warning>

## Produzione

### Nginx + Octane

```nginx theme={null}
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    server_name example.com;
    root /home/forge/example.com/public;

    location /index.php {
        try_files /not_exists @octane;
    }

    location / {
        try_files $uri $uri/ @octane;
    }

    location @octane {
        set $suffix "";

        if ($uri = /index.php) {
            set $suffix ?$query_string;
        }

        proxy_http_version 1.1;
        proxy_set_header Host $http_host;
        proxy_set_header Scheme $scheme;
        proxy_set_header SERVER_PORT $server_port;
        proxy_set_header REMOTE_ADDR $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;

        proxy_pass http://127.0.0.1:8000$suffix;
    }
}
```

### Supervisor

```ini theme={null}
[program:octane]
process_name=%(program_name)s_%(process_num)02d
command=php /home/forge/example.com/artisan octane:start --server=frankenphp --host=127.0.0.1 --port=8000
autostart=true
autorestart=true
user=forge
redirect_stderr=true
stdout_logfile=/home/forge/example.com/storage/logs/octane.log
stopwaitsecs=3600
```

### HTTPS

```ini theme={null}
OCTANE_HTTPS=true
```

### Laravel Cloud

<Steps>
  <Step title="Installa il pacchetto">
    ```bash theme={null}
    composer require laravel/octane
    ```
  </Step>

  <Step title="Attiva Octane in Laravel Cloud">
    Nel cluster compute App attiva "Use Octane as runtime", salva e deploya.
  </Step>
</Steps>

Vedi la [documentazione Laravel Cloud](https://cloud.laravel.com/docs/compute#laravel-octane).

### Reload dopo il deploy

```bash theme={null}
php artisan octane:reload
```


## Related topics

- [Laravel Cloud — la panoramica completa del PaaS dedicato a Laravel](/it/blog/laravel-cloud.md)
- [Creare un server MCP con Laravel](/it/advanced/mcp-server.md)
- [Deployment](/it/deployment.md)
- [Laravel Telescope](/it/telescope.md)
- [Laravel Boost](/it/boost.md)
