shieldon / psr7
1.2.7
2023-06-06 07:59 UTC
Requires
- php: >=7.1.0
- psr/http-factory: ^1.0
- psr/http-message: ^1.1 || ^2.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- phpunit/phpunit: ^9
README
此库是为 Shieldon防火墙2 创建的PSR HTTP实现,完全遵循PSR(PHP标准建议)文档。
- PSR-7(HTTP消息接口)
- PSR-15(HTTP服务器请求处理程序)
- PSR-17(HTTP工厂)
测试状态
Shieldon PSR-HTTP库通过单元测试严格测试,包含几乎所有可能发生的情况。如果您发现任何错误或可以改进此库的地方,请告知我。
测试套件 | 状态 |
---|---|
内置测试仓库 | |
PSR-7集成测试 |
您可以在任何兼容这些PSR的框架中使用它。
安装
composer require shieldon/psr-http
测试
composer install
composer test
快速入门
实现PSR-7在您的PHP应用程序中的最简单方法是查看下面的示例。
创建服务器请求。
$serverRequest = ServerRequestFactory::fromGlobal();
创建请求。
$request = RequestFactory::fromNew();
创建服务器响应
$response = ResponseFactory::fromNew();
创建URI。
// Create a URI contains visitor's information. /** * Assume a visior is viewing your website page, * for example, https://yoursite/en/post1.html */ $uri = UriFactory::fromGlobal(); echo $uri->getPath(); // Outputs: /en/post1.html // Create a URI just a new instance. $uri = UriFactory::fromNew(); echo $uri->getPath(); // Outputs:
创建流实例。
// Create a stream just a new instance. $stream = StreamFactory::fromNew();
创建具有UploadedFile结构的数组。
// Let's see the following example, // assume we have a superglobal $_FILES looks like this. $_FILES = [ 'foo' => [ 'name' => 'example1.jpg', 'type' => 'image/jpeg', 'tmp_name' => '/tmp/php200A.tmp', 'error' => 0, 'size' => 100000, ] ]; $uploadFileArr = UploadedFileFactory::fromGlobal(); echo $uploadFileArr['foo']->getClientFilename(); // Outputs: example1.jpg
目录
-
PSR-17: HTTP工厂
-
RequestFactory
- createRequest
- ::fromNew
(非PSR)
-
ServerRequestFactory
- createServerRequest
- ::fromGlobal
(非PSR)
-
ResponseFactory
- createResponse
- ::fromNew
(非PSR)
-
StreamFactory
-
UploadedFileFactory
- createUploadedFile
- ::fromGlobal
(非PSR)
-
UriFactory
- createUri
- ::fromGlobal
(非PSR)
- ::fromNew
(非PSR)
-
-
PSR-7: HTTP消息接口
-
Message
-
Request (扩展Message)
-
ServerRequest (扩展Request)
-
Response (扩展Message)
-
Stream
-
UploadedFile
-
Uri
-
-
PSR-15: HTTP 服务器请求处理器
如果您需要综合示例,请参阅 单元测试。
处理请求体的行为
Shieldon PSR-HTTP 准备好了用于 RESTful,以下内容解释了 PSR-HTTP 如何处理请求体。
getParsedBody
方法将返回
-
(A) 如果请求方法为
POST
且 Content-Type 是以下类型之一,则返回超级全局变量 $_POST 的数组multipart/form-data
application/x-www-form-urlencode
-
(B) 如果请求符合以下条件,则返回 JSON 对象。
- 请求 Content-Type 为
application/json
- 请求体是有效的 JSON 格式化 字符串。
- 请求方法不是
GET
。
- 请求 Content-Type 为
-
(C) 从 HTTP 构建查询解析的数组
- 条件既不是 A 也不是 B。
- 请求方法不是
GET
。
-
(D) 如果条件不属于以上任何一种,则返回
null
。
总结
条件 | 方法 | Content-type | 解析后的体 |
---|---|---|---|
A | POST | multipart/form-data application/x-www-form-urlencode |
数组 |
B | 除了 GET 之外的所有方法 | application/json | 对象 |
C | 除了 GET 之外的所有方法 | 除了 A 或 B 之外的所有方法 | 数组 |
D | - | - | null |
希望这能帮到您。
作者
Shieldon PSR HTTP 库由来自台湾的 Terry L. 提供。
许可
MIT