shieldon / psr-http
PSR标准HTTP实现。
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的框架上使用它。
安装
composer require shieldon/psr-http
测试
composer install
composer test
快速入门
在PHP应用程序中实现PSR-7的最简单方法,下面是示例。
创建服务器请求。
$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
- __construct
(非 PSR)
- getStream
- moveTo
- getSize
- getError
- getClientFilename
- getClientMediaType
- getErrorMessage
(非 PSR)
- __construct
-
Uri
-
-
PSR-15:HTTP 服务器请求处理器
-
RequestHandler
- __construct
(非 PSR)
- add
- handle
- __construct
-
Middleware
-
如果您在寻找综合示例,请参阅单元测试。
处理请求体的行为
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
。
总结
希望这能帮到您。
作者
Shieldon PSR HTTP 库由来自台湾的 Terry L. 提供。Terry L.
许可
MIT