PSR-7 的快速 PHP7 实现(nyholm/psr7 的分支,移除所有类中的 final 关键字,使其可扩展)

dev-master / 1.4.x-dev 2023-01-22 19:20 UTC

This package is auto-updated.

Last update: 2024-08-22 23:10:07 UTC


README

一个非常轻量级的 PSR-7 实现。非常严格且非常快速。

安装

composer require terablaze/psr7

如果你使用 Symfony Flex,那么所有消息工厂都会注册为服务。

用法

PSR-7 对象不包含任何其他公开方法,除了在 PSR-7 规范 中定义的方法。

创建对象

使用 PSR-17 工厂创建请求、流、URI 等。

$psr17Factory = new \Terablaze\Psr7\Factory\Psr17Factory();
$request = $psr17Factory->createRequest('GET', 'https://teraboxx.com');
$stream = $psr17Factory->createStream('foobar');

发送请求

使用 HTTPlug 或其他 PSR-18(HTTP 客户端),你可以发送请求如下:

composer require kriswallsmith/buzz
$psr17Factory = new \Terablaze\Psr7\Factory\Psr17Factory();
$psr18Client = new \Buzz\Client\Curl($psr17Factory);

$request = $psr17Factory->createRequest('GET', 'https://teraboxx.com');
$response = $psr18Client->sendRequest($request);

创建服务器请求

可以使用 terablaze/psr7-server 包从 PHP 超全局变量创建服务器请求。

composer require terablaze/psr7-server
$psr17Factory = new \Terablaze\Psr7\Factory\Psr17Factory();

$creator = new \Terablaze\Psr7Server\ServerRequestCreator(
    $psr17Factory, // ServerRequestFactory
    $psr17Factory, // UriFactory
    $psr17Factory, // UploadedFileFactory
    $psr17Factory  // StreamFactory
);

$serverRequest = $creator->fromGlobals();

发送响应

composer require laminas/laminas-httphandlerrunner
$psr17Factory = new \Terablaze\Psr7\Factory\Psr17Factory();

$responseBody = $psr17Factory->createStream('Hello world');
$response = $psr17Factory->createResponse(200)->withBody($responseBody);
(new \Laminas\HttpHandlerRunner\Emitter\SapiEmitter())->emit($response);