middlewares/filesystem

使用 Flysystem 保存或读取响应的中间件

v2.0.1 2020-12-03 01:13 UTC

This package is auto-updated.

Last update: 2024-08-29 05:12:29 UTC


README

Latest Version on Packagist Software License Testing Total Downloads

中间件用于从文件保存或读取响应。它使用 Flysystem 作为文件系统处理器,因此您不仅可以使用本地目录,还可以使用任何其他适配器,如 ftpsftpdropbox 等...

要求

安装

此包可以通过 Composer 安装并自动加载,名称为 middlewares/filesystem

composer require middlewares/filesystem

示例

Dispatcher::run([
    Middlewares\Reader::createFromDirectory(__DIR__.'/assets')
]);

读取器

在以下条件下从文件读取响应体

  • 仅允许 GET 方法,否则返回 405 代码。
  • 如果请求路径没有扩展名,则假设它是一个目录,并附加 /index.html。例如:如果请求路径是 /post/23,则使用的文件是 /post/23/index.html
  • 它可以处理 gzip 文件。例如,如果 /post/23/index.html 不存在,但 /post/23/index.html.gz 可用,并且请求头 Accept-Encoding 包含 gzip,则返回它。
  • 也支持 Accept-Ranges,这对于服务器大文件(如视频)非常有用。

使用 ftp 存储的示例

use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Ftp;

$filesystem = new Filesystem(new Ftp([
    'host' => 'ftp.example.com',
    'username' => 'username',
    'password' => 'password',
    'port' => 21,
    'root' => '/path/to/root',
    'passive' => true,
    'ssl' => true,
    'timeout' => 30,
]));

Dispatcher::run([
    new Middlewares\Reader($filesystem)
]);

可选地,您可以提供 Psr\Http\Message\ResponseFactoryInterfacePsr\Http\Message\StreamFactoryInterface,它们将用于创建响应和流。如果它们未定义,则 Middleware\Utils\Factory 将自动检测它们。

$responseFactory = new MyOwnResponseFactory();
$streamFactory = new MyOwnStreamFactory();

$reader = new Middlewares\Reader($filesystem, $responseFactory, $streamFactory);

continueOnError

允许在错误(文件未找到、方法不允许等)发生时继续到下一个中间件。这允许创建一个简单的缓存系统,如下所示

$cache = new Flysystem(new Local(__DIR__.'/path/to/files'));

Dispatcher::run([
    (new Middlewares\Reader($cache))    //read and returns the cached response...
        ->continueOnError(),            //...but continue if the file does not exists

    new Middlewares\Writer($cache),     //save the response in the cache

    new Middlewares\AuraRouter($route), //create a response using, for example, Aura.Router
]);

写入器

如果满足以下所有条件,则将响应内容保存到文件中

  • 方法是 GET
  • 状态码是 200
  • Cache-Control 头部不包含 no-cacheno-store

Reader 行为兼容

  • 如果请求路径没有扩展名,则假设它是一个目录,并附加 /index.html。例如:如果请求路径是 /post/23,则保存的文件是 /post/23/index.html
  • 如果响应被 gzip 压缩(具有头 Content-Encoding: gzip),则文件以 .gz 扩展名保存。例如 /post/23/index.html.gz(而不是 /post/23/index.html)。
$filesystem = new Flysystem(new Local(__DIR__.'/storage'));

Dispatcher::run([
    new Middlewares\Writer($filesystem)
]);

可选地,您还可以提供 Psr\Http\Message\StreamFactoryInterface 作为第二个参数,它将用于创建响应的新主体。如果未定义,则 Middleware\Utils\Factory 将自动检测它。

$streamFactory = new MyOwnStreamFactory();

$reader = new Middlewares\Writer($filesystem, $streamFactory);

辅助工具

createFromDirectory

由于这是最常见的情况,所以 ReaderWriter 都有一个静态方法作为创建实例的快捷方式,使用本地文件系统中的目录

Dispatcher::run([
    Middlewares\Writer::createFromDirectory(__DIR__.'/assets')
    Middlewares\Reader::createFromDirectory(__DIR__.'/assets')
]);

请参阅 变更日志 了解最近更改的详细信息,以及参阅 贡献指南 了解贡献详情。

MIT 许可证 (MIT)。请参阅 许可证 了解更多信息。