Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I ensure singletons persist between requests in Laravel Octane


How can I ensure singletons persist between requests in Laravel Octane


To ensure singletons persist between requests in Laravel Octane, you can follow these steps:

1. When registering a singleton in the service container, pass a callback instead of the actual instance of the dependency. This ensures the dependency is only resolved once, even if it's requested multiple times.

php
// Instead of...
$this->app->singleton(Service::class, function ($app) {
    return new Service($app['config']);
});

// Do...
$this->app->singleton(Service::class, function ($app) {
    return new Service(fn() => Container::getInstance()['config']);
});

2. Alternatively, you can use the `config()` helper function inside the service class instead of injecting the configuration repository. This achieves the same result of only resolving the configuration repository once.

php
// Instead of...
$this->app->singleton(Service::class, function ($app) {
    return new Service($app['config']);
});

// Do...
$this->app->singleton(Service::class, function ($app) {
    return new Service(fn() => config());
});

3. Singletons that are resolved during the application bootstrapping (in service providers) will persist between requests on Octane. However, singletons resolved during request handling will be registered in a sandbox container that is destroyed after handling the request.

4. To ensure singletons persist between requests on Octane, you can either resolve them in your service providers or add them to the `warm` array in the Octane configuration file:

php
// In the Octane configuration file
'warm' => [
    ...Octane::defaultServicesToWarm(),
    Service::class,
],

5. If you have a package that registers and resolves a singleton inside a service provider, and you want to flush that instance before every request, you can add it to the `flush` array in the Octane configuration file:

php
// In the Octane configuration file
'flush' => [
    Service::class,
],

By following these steps, you can ensure that your singletons persist between requests when running your Laravel application on Octane, which is crucial for maintaining application state and improving performance.[1][3]

Citations:
[1] https://divinglaravel.com/laravel-octane-bootstrapping-the-application-and-handling-requests
[2] https://www.prismetric.com/laravel-octane/
[3] https://laravel.com/docs/11.x/octane
[4] https://archive.org/details/github.com-laravel-octane_-_2021-04-08_23-10-36
[5] https://www.studocu.com/id/document/universitas-amikom-yogyakarta/web-programming/laravel-octane-laravel-the-php-framework-for-web-artisans/46587841