定制 silber/page-cache 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

silber/page-cache

Composer 安装命令:

composer require silber/page-cache

包简介

Caches responses as static files on disk for lightning fast page loads.

关键字:

README 文档

README

Build Status Latest Stable Version Total Downloads License

This package allows you to easily cache responses as static files on disk for lightning fast page loads.

Introduction

While static site builders such as Jekyll and Jigsaw are extremely popular these days, dynamic PHP sites still offer a lot of value even for a site that is mostly static. A proper PHP site allows you to easily add dynamic functionality wherever needed, and also means that there's no build step involved in pushing updates to the site.

That said, for truly static pages on a site, there really is no reason to have to boot up a full PHP app just to serve a static page. Serving a simple HTML page from disk is infinitely faster and less taxing on the server.

The solution? Full page caching.

Using the middleware included in this package, you can selectively cache the response to disk for any given request. Subsequent calls to the same page will be served directly as a static HTML page!

Installation

Note: The current version of Page Cache requires PHP 8.2+ and Laravel 11+.

If you're on Laravel v5-v10, use Page Cache v1.0.9.

Install the page-cache package with composer:

$ composer require silber/page-cache

Middleware

Open app/Http/Kernel.php and add a new item to the web middleware group:

protected $middlewareGroups = [
    'web' => [
        \Silber\PageCache\Middleware\CacheResponse::class,
        /* ... keep the existing middleware here */
    ],
];

The middleware is smart enough to only cache responses with a 200 HTTP status code, and only for GET requests.

If you want to selectively cache only specific requests to your site, you should instead add a new mapping to the middlewareAliases array:

protected $middlewareAliases = [
    'page-cache' => \Silber\PageCache\Middleware\CacheResponse::class,
    /* ... keep the existing mappings here */
];

Once registered, you can then use this middleware on individual routes.

URL rewriting

In order to serve the static files directly once they've been cached, you need to properly configure your web server to check for those static files.

  • For nginx:

    Update your location block's try_files directive to include a check in the page-cache directory:

    location = / {
        try_files /page-cache/pc__index__pc.html /index.php?$query_string;
    }
    
    location / {
        try_files $uri $uri/ /page-cache/$uri.html /page-cache/$uri.json /page-cache/$uri.xml /index.php?$query_string;
    }
  • For apache:

    Open public/.htaccess and add the following before the block labeled Handle Front Controller:

    # Serve Cached Page If Available...
    RewriteCond %{REQUEST_URI} ^/?$
    RewriteCond %{DOCUMENT_ROOT}/page-cache/pc__index__pc.html -f
    RewriteRule .? page-cache/pc__index__pc.html [L]
    RewriteCond %{DOCUMENT_ROOT}/page-cache%{REQUEST_URI}.html -f
    RewriteRule . page-cache%{REQUEST_URI}.html [L]
    RewriteCond %{DOCUMENT_ROOT}/page-cache%{REQUEST_URI}.json -f
    RewriteRule . page-cache%{REQUEST_URI}.json [L]
    RewriteCond %{DOCUMENT_ROOT}/page-cache%{REQUEST_URI}.xml -f
    RewriteRule . page-cache%{REQUEST_URI}.xml [L]

Ignoring the cached files

To make sure you don't commit your locally-cached files to your git repository, add this line to your .gitignore file:

/public/page-cache

Usage

Using the middleware

Note: If you've added the middleware to the global web group, then all successful GET requests will automatically be cached. No need to put the middleware again directly on the route.

If you instead registered it in middlewareAliases, you should use the middleware on whichever routes you want to be cached.

To cache the response of a given request, use the page-cache middleware:

Route::middleware('page-cache')->get('posts/{slug}', 'PostController@show');

Every post will now be cached to a file under the public/page-cache directory, closely matching the URL structure of the request. All subsequent requests for this post will be served directly from disk, never even hitting your app!

Clearing the cache

Since the responses are cached to disk as static files, any updates to those pages in your app will not be reflected on your site. To update pages on your site, you should clear the cache with the following command:

php artisan page-cache:clear

As a rule of thumb, it's good practice to add this to your deployment script. That way, whenever you push an update to your site, the page cache will automatically be cleared.

If you're using Forge's Quick Deploy feature, you should add this line to the end of your Deploy Script. This'll ensure that the cache is cleared whenever you push an update to your site.

You may optionally pass a URL slug to the command, to only delete the cache for a specific page:

php artisan page-cache:clear {slug}

To clear everything under a given path, use the --recursive flag:

php artisan page-cache:clear {slug} --recursive

For example, imagine you have a category resource under /categories, with the following cached pages:

  • /categories/1
  • /categories/2
  • /categories/5

To clear the cache for all categories, use --recursive with the categories path:

php artisan page-cache:clear categories --recursive

Customizing what to cache

By default, all GET requests with a 200 HTTP response code are cached. If you want to change that, create your own middleware that extends the package's base middleware, and override the shouldCache method with your own logic.

  1. Run the make:middleware Artisan command to create your middleware file:

    php artisan make:middleware CacheResponse
    
  2. Replace the contents of the file at app/Http/Middleware/CacheResponse.php with this:

    <?php
    
    namespace App\Http\Middleware;
    
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use Silber\PageCache\Middleware\CacheResponse as BaseCacheResponse;
    
    class CacheResponse extends BaseCacheResponse
    {
        protected function shouldCache(Request $request, Response $response)
        {
            // In this example, we don't ever want to cache pages if the
            // URL contains a query string. So we first check for it,
            // then defer back up to the parent's default checks.
            if ($request->getQueryString()) {
                return false;
            }
    
            return parent::shouldCache($request, $response);
        }
    }
  3. Finally, update the middleware references in your app/Http/Kernel.php file, to point to your own middleware.

License

The Page Cache package is open-sourced software licensed under the MIT license.

silber/page-cache 适用场景与选型建议

silber/page-cache 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 469.11k 次下载、GitHub Stars 达 1.26k, 最近一次更新时间为 2016 年 07 月 20 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「cache」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 silber/page-cache 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 silber/page-cache 我们能提供哪些服务?
定制开发 / 二次开发

基于 silber/page-cache 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 469.11k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1259
  • 点击次数: 30
  • 依赖项目数: 4
  • 推荐数: 0

GitHub 信息

  • Stars: 1256
  • Watchers: 18
  • Forks: 120
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2016-07-20