varnish equivalent package in laravel for caching

Viewed 669

I am on my way to Improving the performance of my Laravel app. After googling for sometime I've implemented some of the best practices to increase the performance.

But now I came to realise that my laravel app executes lot of select queries and the data on my site don't changes so often. Therefore I decided to implement caching and I came to know that varnish is the best for this purpose. But that's a quite complicated thing to get started with. Therefore I want to know If there is equivalent solution which is not so complicated as varnish. I am looking for a Laravel package that automatically cache the response generated by laravel app.

1 Answers

You can Implement cashing by using a middleware in Laravel. Here is the code of middleware that I am using.

public function handle($request, Closure $next, $ttl=1440)
{
    if(authenticate_user() != null || $request->isMethod('post') || session()->get('success'))
        return $next($request);
    $params = $request->query(); unset($params['_method']); ksort($params);
    $key = md5(url()->current().'?'.http_build_query($params));
    if($request->get('_method')=='purge')
        Cache::forget($key);
    if(Cache::has($key)){
        $cache = Cache::get($key);
        $response = response($cache['content']);
        $response->header('X-Proxy-Cache', 'HIT');
    }
    else {
        $response = $next($request);
        if(!empty($response->content()))
            Cache::put($key,['content' => $response->content(), 'headers' => array_map(function($element){ return implode(',', $element); }, $response->headers->all())],$ttl);
        $response->header('X-Proxy-Cache', 'MISS');
    }

    return $response;
}

Here is the explanation of the above code. Improve server performance by caching server response

Related