Laravel/Octane: How to reset route controllers' state

582 Views Asked by At

In Laravel v9/Octane/Swoole, I do have private properties in route controllers, e.g.

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;

class SignupController extends Controller
{
    /** @var ?\App\SignupCode A verification code object */
    protected $code;

It looks like the property is "shared" between requests under Octane. I have more controllers like this. How do I make sure the controller state gets reset on every request? I've read the whole Octane documentation a few times, and it's still unclear how to do that.

1

There are 1 best solutions below

0
On

I solved it by created listener

<?php

namespace App\Listeners;

use Illuminate\Routing\Router;

class ResetControllerState
{
    /**
     * Handle the event.
     *
     * @param  mixed  $event
     * @return void
     */
    public function handle($event): void
    {
        /** @var Router $router */
        $router = $event->sandbox->make(Router::class);

        $currentRoute = $router->current();

        if($currentRoute && $currentRoute->controller)
            $currentRoute->controller = null;

    }
}

and add it to array of listeners in octane config

RequestReceived::class => [
    ...Octane::prepareApplicationForNextOperation(),
    ...Octane::prepareApplicationForNextRequest(),
    \App\Listeners\ResetControllerState::class
    //
],

I do not know what the consequences may be, but so far it works well.