gmponos / http-message-util
一组用于操作PSR-7 HTTP请求/响应的实用工具
v0.2.0
2019-01-06 16:49 UTC
Requires
- php: ^7.1
- ext-json: *
- psr/http-message: ^1.0
Requires (Dev)
- guzzlehttp/psr7: ^1.5
- phpunit/phpunit: ^7.5
- squizlabs/php_codesniffer: ^3.2
This package is auto-updated.
Last update: 2024-09-07 05:15:01 UTC
README
本包包含用于操作PSR-7请求/响应对象的有用实用类。
重要说明
- 此包仍在0.x.x版本中。根据语义版本控制,在0.x.x版本期间可能会发生重大更改。如果您在生产的项目中使用此包,请使用Composer锁定此包到特定版本,例如^0.3.0。
描述
假设您有一个向API发送JSON主体的类。您很可能会有以下代码
之前
<?php class SendNotification { private $client; private $requestFactory; public function __construct(ClientInterface $client, RequestFactoryInterface $requestFactory) { // PSR-17 factory $this->requestFactory = $requestFactory; // PSR-18 HTTP Client $this->client = $client; } public function send(string $email, string $message): \Psr\Http\Message\ResponseInterface { $request = $this->requestFactory->create('GET', 'http://www.testurl.com'); $body = $request->getBody(); if ($body->isSeekable() === false || $body->isWritable() === false) { throw new \InvalidArgumentException('Can not modify a request with non writable body.'); } $content = json_encode(['email' => $email, 'message' => $message]); if (JSON_ERROR_NONE !== json_last_error()) { throw new \InvalidArgumentException('Json encoding failed: ' . json_last_error()); } $body->write($content); $body->rewind(); $request = $request->withHeader('Content-Type', 'application/json'); return $this->client->sendRequest($request); } }
使用实用工具
<?php use HttpMessageUtil\RequestUtil; class SendNotification { private $client; private $requestFactory; public function __construct(ClientInterface $client, RequestFactoryInterface $requestFactory) { // PSR-17 factory $this->requestFactory = $requestFactory; // PSR-18 HTTP Client $this->client = $client; } public function send(string $email, string $message): \Psr\Http\Message\ResponseInterface { $request = $this->requestFactory->create('GET', 'http://www.testurl.com'); $request = RequestUtil::withJsonBody($request, [ 'email' => $email, 'message' => $message ]); return $this->client->sendRequest($request); } }
安装
您可以通过Composer安装此包
$ composer require gmponos/http-message-util
变更日志
有关最近更改的更多信息,请参阅变更日志。
测试
- 从bash中运行
composer install
。 - 从bash中运行
composer tests
。
许可证
MIT许可证(MIT)。有关更多信息,请参阅许可证文件。