Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Caching of data in request for input() and body(), maybe others #26

Open
patrickvuarnoz opened this issue Nov 26, 2024 · 1 comment
Open

Comments

@patrickvuarnoz
Copy link

The methods input() and body() are called from different places in the request class. One such place being get(). If a controller wants to update or create a model like in the following code ...

$flight = new Flight;
$flight->name = request()->get('name');
$flight->number = request()->get('number');
$flight->date = request()->get('date');
$flight->save();

... then the whole data from the request will get parsed, evaluated and sanitized 3 times. It would be better if the data would only be parsed once and only upon usage. Something like the following code might achieve this:

class Request {
    ...
    // Keep a cached version of the result of input()
    protected static $input = null;
    ...
    public static function input(bool $safeData = true)
    {
        // Check if input was calculated before, if yes, return it immediately
        if (static::$input) return static::$input;

        // Handling for first-time processing
        $handler = fopen('php://input', 'r');
        $data = stream_get_contents($handler);
        $contentType = Headers::get('Content-Type') ?? '';
        ...

        // Cache data
        static::$input = $safeData ? \Leaf\Anchor::sanitize($data) : $data;

        // Return
        return static::$input;
    }
}
@mychidarko
Copy link
Member

@patrickvuarnoz that's correct, yes we can save a bit of performance by implementing a caching layer on the request, however, something like this won't work because of other systems like Swoole otherwise we risk having data crossing into subsequent requests.

We have plans for a caching layer all over Leaf, but there are a few more pressing things at the moment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants