search
HomePHP FrameworkLaravelDetailed explanation of how to use ETag and conditional headers for caching

Laravel API Performance Optimization: Caching with ETag and Conditional Headers

When writing an application with separate front-end and back-end, you have to start thinking about what kind of requests the front-end client will submit to the API to get data from the back-end again, even if you just want to verify whether the front-end cache can Real-time updates of added data. Based on the above requirements, you can use the ETag header and conditional requests.

In this blog post, I will briefly outline what ETag, If-None-Match and If-Match are to do etc., and then take a look at how I apply these to our package, which can quickly implement it into your application.

What is it

Let’s start with the meat and potatoes of it all, the ETag header. This header is a value that represents the response body in the exact state it is in. In many cases the value of ETag will be the hash value of the content, as this is the easiest way to generate and guarantee a unique identifier for the response data.

In order to ensure that the ETag header is available, we must use conditional requests. The first condition we need to set is the If-None-Match header, which is a request header for GET. After the backend receives this header, it needs to be compared with the current content. If the values ​​match, only the 304 status code will be returned. Compared with obtaining the entity resource, the response result data itself is very small. All this is very simple to implement: if your first GET request to obtain a resource returns an ETag data, your browser will automatically The request configuration If-None-Match header.

This means that if your backend simply implements etag and if-none-match, you can reduce the data transferred from your API to the frontend quantity.

The second request condition uses the if-match header. This is used to prevent mid-air collisions. In layman's terms, if we want to update data in the backend, but our frontend data is out of date, the update of the backend should be terminated, and there should be a reminder on the frontend. This is similar to how if-none-match works. After obtaining the resource containing the ETag value, you can submit a PATCH request and set a equal to the ETag value you previously received. If-Match value. The backend will then check whether the etag value of the resource currently available on the server matches the resource you sent. If there is a match, your update will be allowed. If there is no match, the 412 status code will be returned to let the front end know that the conditions do not match.

How to use

If you want to use this conditional request plug-in package in the laravel project, you can use the following command to install it:

$ composer require werk365/etagconditionals

Then add etag middleware to your route and you can use it. If you want to study how middleware works, or if you want to implement this function without using our plug-in package, please read on!

SetEtag Middleware

As you may have guessed, we can easily implement this function through middleware. Laravel actually provides us with a SetCacheHeaders middleware to set the ETag header, but it does not support HEAD requests. SetEtag The content of the middleware looks like this:

    public function handle(Request $request, Closure $next)
    {
        // Handle request
        $method = $request->getMethod();

        // Support using HEAD method for checking If-None-Match
        if ($request->isMethod('HEAD')) {
            $request->setMethod('GET');
        }

        //Handle response
        $response = $next($request);

        // Setting etag
        $etag = md5($response->getContent());
        $response->setEtag($etag);

        $request->setMethod($method);

        return $response;
    }

The first thing we need to do is get the requested method, in case we want to modify it. Then, when we are processing the HEAD request, we modify it to a GET request to ensure that the requested content has been loaded and can be encrypted. After this, we jump to the response body content that has been encrypted using the md5() method. Before returning the response, we will use the encrypted hash value as the ETag header and set the original request method back.

IfNoneMatch Middleware

This is another relatively simple method. Let's take a look at the code first:

    public function handle(Request $request, Closure $next)
    {
        // Handle request
        $method = $request->getMethod();

        // Support using HEAD method for checking If-None-Match
        if ($request->isMethod('HEAD')) {
            $request->setMethod('GET');
        }

        //Handle response
        $response = $next($request);

        $etag = '"'.md5($response->getContent()).'"';
        $noneMatch = $request->getETags();

        if (in_array($etag, $noneMatch)) {
            $response->setNotModified();
        }

        $request->setMethod($method);

        return $response;
    }

这个开头与  SetEtag 中间件相似,将确保我们可以再次处理 HEAD 请求,并根据响应内容生成 hash值。注意这种情况下我们需要将hash值用双引号包裹。双引号包裹 ETag头,然后在setEtag中间件中 setEtag()方法自动包裹hash。有了hash值后,我们可以轻松的与 If-None-Match头进行比较。由于该头可以自动加载无限个hash,并且 getETags()方法会将它们以数组形式返回,所以我们可以核对新生成的值是否存在于数组中。如果确实有匹配,我们可以在响应中使用 setNotModified()设置 304 的状态码。

IfMatch 中间件

处理 If-Match 将稍微复杂一些。这个问题归结于:我们需要找到一种方法,用来获取应该更新的当前版本的内容。这可以用多种方式实现。

  • 你可以使用 HTTP 客户端对相同资源从外部发起 GET 请求
  • 你可以查看当前请求将执行的操作, 而不是调用与之等价的 GET 请求( 例如,调用控制器上的 show() 方法)
  • 或者你可以通过内部发起一个新的 GET 请求。

在构建这个中间件时,我开始尝试使用第二个选项。出于某种原因,这对我来说似乎是最好的选择。我成功地创建了一个完全可以工作的版本,但我对结果并不满意。为了让它工作,我需要做一些假设,预设一些限制,并做了太多的工作,而我只需要创建一个新的请求就可以了。

当我们要发起一个新的请求来获取当前版本资源的时候,代码是下面这样的:

    public function handle(Request $request, Closure $next)
    {
        // 只有请求方式是 PATCH 并且已经设置了 If-Match 头
        if (! ($request->isMethod('PATCH') && $request->hasHeader('If-Match'))) {
            return $next($request);
        }

        // 对同一个点创建新的 GET 请求,
        // 复制和添加请求头,让中间件能忽略本次请求
        $getRequest = Request::create($request->getRequestUri(), 'GET');
        $getRequest->headers = $request->headers;
        $getRequest->headers->set('X-From-Middleware', 'IfMatch');
        $getResponse = app()->handle($getRequest);

        // Get content from response object and get hashes from content and etag
        $getContent = $getResponse->getContent();
        $getEtag = '"'.md5($getContent).'"';
        $ifMatch = $request->header('If-Match');

        // 比较当前和请求携带的 hash 值
        if ($getEtag !== $ifMatch) {
            return response(null, 412);
        }

        return $next($request);

所有这些中间件都将在请求生命周期开始时运行。首先,我们将过滤掉任何非 PATCH 请求或请求头中没有 If Match 的请求。之后,我们将向同一个端点发出一个新的 GET 请求,并从原来的请求中复制请求头,以便新请求可以通过身份验证中间件和其他约束。

使用这个新请求的响应,我们将再次生成一个哈希,以便与发送的哈希进行比较。如果哈希匹配,请求将被中间件允许通过。如果不匹配,将返回状态代码为 412 的请求响应。

通过使用这三个中间件,你可以在你的 Laravel 应用程序中轻松处理 ETag 和条件请求。

软件包:https://github.com/365Werk/etagconditionals

原文地址:https://hergen.nl/caching-your-laravel-api-with-etag-and-conditional-requests

译文地址:https://learnku.com/laravel/t/55539

The above is the detailed content of Detailed explanation of how to use ETag and conditional headers for caching. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Laravel's Backend Capabilities: Databases, Logic, and MoreLaravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AM

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

Laravel's Versatility: From Simple Sites to Complex SystemsLaravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AM

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Laravel (PHP) vs. Python: Development Environments and EcosystemsLaravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AM

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

Laravel and the Backend: Powering Web Application LogicLaravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Why is Laravel so popular?Why is Laravel so popular?Apr 02, 2025 pm 02:16 PM

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Which is better, Django or Laravel?Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

Which is better PHP or Laravel?Which is better PHP or Laravel?Mar 27, 2025 pm 05:31 PM

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

Is Laravel a frontend or backend?Is Laravel a frontend or backend?Mar 27, 2025 pm 05:31 PM

LaravelisabackendframeworkbuiltonPHP,designedforwebapplicationdevelopment.Itfocusesonserver-sidelogic,databasemanagement,andapplicationstructure,andcanbeintegratedwithfrontendtechnologieslikeVue.jsorReactforfull-stackdevelopment.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment