shieldon/psr-http

PSR标准HTTP实现。

1.2.7 2023-06-06 07:59 UTC

This package is auto-updated.

Last update: 2024-09-06 11:14:07 UTC


README

build codecov Scrutinizer Code Quality License: MIT

这个库是为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

目录

如果您在寻找综合示例,请参阅单元测试

处理请求体的行为

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
  • (C) 从 HTTP 构建查询解析的数组

    • 条件既不是 A 也不是 B。
    • 请求方法不是 GET
  • (D) 如果条件不满足上述任何一种,则返回 null

总结

希望这能帮到您。

作者

Shieldon PSR HTTP 库由来自台湾的 Terry L. 提供。Terry L.

许可

MIT

参考

  • PSR-7(HTTP 消息接口)
  • PSR-15(HTTP 服务器请求处理器)
  • PSR-17(HTTP 工厂)