「PSR 规范」PSR-7 HTTP 消息接口规范

HTTP消息接口

此文档描述了 RFC 7230RFC 7231 HTTP 消息传递的接口,还有 RFC 3986 里对 HTTP 消息的 URIs 使用。

HTTP 消息是 Web 技术发展的基础。浏览器或 HTTP 客户端如 curl 生成发送 HTTP 请求消息到 Web 服务器,Web 服务器响应 HTTP 请求。服务端的代码接受 HTTP 请求消息后返回 HTTP 响应消息。

通常 HTTP 消息对于终端用户来说是不可见的,但是作为 Web 开发者,我们需要知道 HTTP 机制,如何发起、构建、取用还有操纵 HTTP 消息,知道这些原理,以助我们刚好的完成开发任务,无论这个任务是发起一个 HTTP 请求,或者处理传入的请求。

每一个 HTTP 请求都有专属的格式:

  1. POST /path HTTP/1.1
  2. Host: example.com
  3. foo=bar&baz=bat

按照顺序,第一行的各个字段意义为: HTTP 请求方法、请求的目标地址(通常是一个绝对路径的 URI 或 者路径),HTTP 协议。

接下来是 HTTP 头信息,在这个例子中:目的主机。接下来是空行,然后是消息内容。

HTTP 返回消息有类似的结构:

  1. HTTP/1.1 200 OK
  2. Content-Type: text/plain
  3. 这是返回的消息内容

按照顺序,第一行为状态行,包括 HTTP 协议版本,HTTP 状态码,描述文本。

和 HTTP 请求类似的,接下来是 HTTP 头信息,在这个例子中:内容类型。接下来是空行,然后是消息内容。

此文档探讨的是 HTTP 请求消息接口,和构建 HTTP 消息需要的元素数据定义。

参考资料

关于「能愿动词」的使用

为了避免歧义,文档大量使用了「能愿动词」,对应的解释如下:

  • 必须 (MUST):绝对,严格遵循,请照做,无条件遵守;
  • 一定不可 (MUST NOT):禁令,严令禁止;
  • 应该 (SHOULD) :强烈建议这样做,但是不强求;
  • 不该 (SHOULD NOT):强烈不建议这样做,但是不强求;
  • 可以 (MAY)可选 (OPTIONAL) :选择性高一点,在这个文档内,此词语使用较少;

参见:RFC 2119

1. 规范详情

1.1 消息

一个 HTTP 消息,指定是一个从客户端发往服务器端的请求,或者是服务器端返回客户端的响应。对应的两 个消息接口:Psr\Http\Message\RequestInterfacePsr\Http\Message\ResponseInterface

这个两个接口都继承于 Psr\Http\Message\MessageInterface。虽然你 可以 实现 Psr\Http\Message\MessageInterface 接口,但是,最重要的,你 必须 实现 Psr\Http\Message\RequestInterfacePsr\Http\Message\ResponseInterface 接口。

从现在开始,为了行文的方便,我们提到这些接口的时候,都会把命名空间 Psr\Http\Message 去除掉。

1.2 HTTP 头信息

大小写不敏感的字段名字

HTTP 消息包含大小写不敏感头信息。使用 MessageInterface 接口来设置和获取头信息,大小写 不敏感的定义在于,如果你设置了一个 Foo 的头信息,foo 的值会被重写,你也可以通过 foo 来 拿到 FoO 头对应的值。

  1. $message = $message->withHeader('foo', 'bar');
  2. echo $message->getHeaderLine('foo');
  3. // 输出: bar
  4. echo $message->getHeaderLine('FOO');
  5. // 输出: bar
  6. $message = $message->withHeader('fOO', 'baz');
  7. echo $message->getHeaderLine('foo');
  8. // 输出: baz

虽然头信息可以用大小写不敏感的方式取出,但是接口实现类 必须 保持自己的大小写规范,特别是用 getHeaders() 方法输出的内容。

因为一些非标准的 HTTP 应用程序,可能会依赖于大小写敏感的头信息,所有在此我们把主宰 HTTP 大小写的权利开放出来,以适用不同的场景。

对应多条数组的头信息

为了适用一个 HTTP 「键」可以对应多条数据的情况,我们使用字符串配合数组来实现,你可以从一个 MessageInterface 取出数组或字符串,使用 getHeaderLine($name) 方法可以获取通过逗号分割的不区分大小写的字符串形式的所有值。也可以通过 getHeader($name) 获取数组形式头信息的所有值。

  1. $message = $message
  2. ->withHeader('foo', 'bar')
  3. ->withAddedHeader('foo', 'baz');
  4. $header = $message->getHeaderLine('foo');
  5. // $header 包含: 'bar, baz'
  6. $header = $message->getHeader('foo');
  7. // ['bar', 'baz']

注意:并不是所有的头信息都可以适用逗号分割(例如 Set-Cookie),当处理这种头信息时候, MessageInterace 的继承类 应该 使用 getHeader($name) 方法来获取这种多值的情况。

主机信息

在请求中,Host 头信息通常和 URI 的 host 信息,还有建立起 TCP 连接使用的 Host 信息一致。 然而,HTTP 标准规范允许主机 host 信息与其他两个不一样。

在构建请求的时候,如果 host 头信息未提供的话,实现类库 必须 尝试着从 URI 中提取 host 信息。

RequestInterface::withUri() 会默认的,从传参的 UriInterface 实例中提取 host , 并替代请求中原有的 host 信息。

你可以提供传参第二个参数为 true 来保证返回的消息实例中,原有的 host 头信息不会被替代掉。

以下表格说明了当 withUri() 的第二个参数被设置为 true 的时,返回的消息实例中调用 getHeaderLine('Host') 方法会返回的内容:

请求 Host 头信息1 请求 URI 中的 Host 信息2 传参进去 URI 的 Host 3 结果
‘’ ‘’ ‘’ ‘’
‘’ foo.com ‘’ foo.com
‘’ foo.com bar.com foo.com
foo.com ‘’ bar.com foo.com
foo.com bar.com baz.com foo.com
  • 1 当前请求的 Host 头信息。
  • 2 当前请求 URI 中的 Host 信息。
  • 3 通过 withUri() 传参进入的 URI 中的 host 信息。

1.3 数据流

HTTP 消息包含开始的一行、头信息、还有消息的内容。HTTP 的消息内容有时候可以很小,有时候确是 非常巨大。尝试使用字符串的形式来展示消息内容,会消耗大量的内存,使用数据流的形式来读取消息 可以解决此问题。StreamInterface 接口用来隐藏具体的数据流读写实现。在一些情况下,消息 类型的读取方式为字符串是能容许的,可以使用 php://memory 或者 php://temp

StreamInterface 暴露出来几个接口,这些接口允许你读取、写入,还有高效的遍历内容。

数据流使用这个三个接口来阐明对他们的操作能力:isReadable()isWritable()isSeekable()。这些方法可以让数据流的操作者得知数据流能否能提供他们想要的功能。

每一个数据流的实例,都会有多种功能:可以只读、可以只写、可以读和写,可以随机读取,可以按顺序读取等。

最终,StreamInterface 定义了一个 __toString() 的方法,用来一次性以字符串的形式输出 所有消息内容。

与请求和响应的接口不同的是,StreamInterface 并不强调不可修改性。因为在 PHP 的实现内,基 本上没有办法保证不可修改性,因为指针的指向,内容的变更等状态,都是不可控的。作为读取者,可以 调用只读的方法来返回数据流,以最大程度上保证数据流的不可修改性。使用者要时刻明确的知道数据 流的可修改性,建议把数据流附加到消息实例中,来强迫不可修改的特性。

1.4 请求目标和 URI

翻译到此先告一段落,此规范篇幅有点过长,需要消耗的时间挺长的,暂且翻译至此,他日再战。

Per RFC 7230, request messages contain a “request-target” as the second segment of the request line. The request target can be one of the following forms:

  • origin-form, which consists of the path, and, if present, the query string; this is often referred to as a relative URL. Messages as transmitted over TCP typically are of origin-form; scheme and authority data are usually only present via CGI variables.
  • absolute-form, which consists of the scheme, authority (“[user-info@]host[:port]”, where items in brackets are optional), path (if present), query string (if present), and fragment (if present). This is often referred to as an absolute URI, and is the only form to specify a URI as detailed in RFC 3986. This form is commonly used when making requests to HTTP proxies.
  • authority-form, which consists of the authority only. This is typically used in CONNECT requests only, to establish a connection between an HTTP client and a proxy server.
  • asterisk-form, which consists solely of the string *, and which is used with the OPTIONS method to determine the general capabilities of a web server.

Aside from these request-targets, there is often an ‘effective URL’ which is separate from the request target. The effective URL is not transmitted within an HTTP message, but it is used to determine the protocol (http/https), port and hostname for making the request.

The effective URL is represented by UriInterface. UriInterface models HTTP and HTTPS URIs as specified in RFC 3986 (the primary use case). The interface provides methods for interacting with the various URI parts, which will obviate the need for repeated parsing of the URI. It also specifies a __toString() method for casting the modeled URI to its string representation.

When retrieving the request-target with getRequestTarget(), by default this method will use the URI object and extract all the necessary components to construct the origin-form. The origin-form is by far the most common request-target.

If it’s desired by an end-user to use one of the other three forms, or if the user wants to explicitly override the request-target, it is possible to do so with withRequestTarget().

Calling this method does not affect the URI, as it is returned from getUri().

For example, a user may want to make an asterisk-form request to a server:

  1. $request = $request
  2. ->withMethod('OPTIONS')
  3. ->withRequestTarget('*')
  4. ->withUri(new Uri('https://example.org/'));

This example may ultimately result in an HTTP request that looks like this:

  1. OPTIONS * HTTP/1.1

But the HTTP client will be able to use the effective URL (from getUri()), to determine the protocol, hostname and TCP port.

An HTTP client MUST ignore the values of Uri::getPath() and Uri::getQuery(), and instead use the value returned by getRequestTarget(), which defaults to concatenating these two values.

Clients that choose to not implement 1 or more of the 4 request-target forms, MUST still use getRequestTarget(). These clients MUST reject request-targets they do not support, and MUST NOT fall back on the values from getUri().

RequestInterface provides methods for retrieving the request-target or creating a new instance with the provided request-target. By default, if no request-target is specifically composed in the instance, getRequestTarget() will return the origin-form of the composed URI (or “/“ if no URI is composed). withRequestTarget($requestTarget) creates a new instance with the specified request target, and thus allows developers to create request messages that represent the other three request-target forms (absolute-form, authority-form, and asterisk-form). When used, the composed URI instance can still be of use, particularly in clients, where it may be used to create the connection to the server.

1.5 Server-side Requests

RequestInterface provides the general representation of an HTTP request message. However, server-side requests need additional treatment, due to the nature of the server-side environment. Server-side processing needs to take into account Common Gateway Interface (CGI), and, more specifically, PHP’s abstraction and extension of CGI via its Server APIs (SAPI). PHP has provided simplification around input marshaling via superglobals such as:

  • $_COOKIE, which deserializes and provides simplified access for HTTP cookies.
  • $_GET, which deserializes and provides simplified access for query string arguments.
  • $_POST, which deserializes and provides simplified access for urlencoded parameters submitted via HTTP POST; generically, it can be considered the results of parsing the message body.
  • $_FILES, which provides serialized metadata around file uploads.
  • $_SERVER, which provides access to CGI/SAPI environment variables, which commonly include the request method, the request scheme, the request URI, and headers.

ServerRequestInterface extends RequestInterface to provide an abstraction around these various superglobals. This practice helps reduce coupling to the superglobals by consumers, and encourages and promotes the ability to test request consumers.

The server request provides one additional property, “attributes”, to allow consumers the ability to introspect, decompose, and match the request against application-specific rules (such as path matching, scheme matching, host matching, etc.). As such, the server request can also provide messaging between multiple request consumers.

1.6 Uploaded files

ServerRequestInterface specifies a method for retrieving a tree of upload files in a normalized structure, with each leaf an instance of UploadedFileInterface.

The $_FILES superglobal has some well-known problems when dealing with arrays of file inputs. As an example, if you have a form that submits an array of files — e.g., the input name “files”, submitting files[0] and files[1] — PHP will represent this as:

  1. array(
  2. 'files' => array(
  3. 'name' => array(
  4. 0 => 'file0.txt',
  5. 1 => 'file1.html',
  6. ),
  7. 'type' => array(
  8. 0 => 'text/plain',
  9. 1 => 'text/html',
  10. ),
  11. /* etc. */
  12. ),
  13. )

instead of the expected:

  1. array(
  2. 'files' => array(
  3. 0 => array(
  4. 'name' => 'file0.txt',
  5. 'type' => 'text/plain',
  6. /* etc. */
  7. ),
  8. 1 => array(
  9. 'name' => 'file1.html',
  10. 'type' => 'text/html',
  11. /* etc. */
  12. ),
  13. ),
  14. )

The result is that consumers need to know this language implementation detail, and write code for gathering the data for a given upload.

Additionally, scenarios exist where $_FILES is not populated when file uploads occur:

  • When the HTTP method is not POST.
  • When unit testing.
  • When operating under a non-SAPI environment, such as ReactPHP.

In such cases, the data will need to be seeded differently. As examples:

  • A process might parse the message body to discover the file uploads. In such cases, the implementation may choose not to write the file uploads to the file system, but instead wrap them in a stream in order to reduce memory, I/O, and storage overhead.
  • In unit testing scenarios, developers need to be able to stub and/or mock the file upload metadata in order to validate and verify different scenarios.

getUploadedFiles() provides the normalized structure for consumers. Implementations are expected to:

  • Aggregate all information for a given file upload, and use it to populate a Psr\Http\Message\UploadedFileInterface instance.
  • Re-create the submitted tree structure, with each leaf being the appropriate Psr\Http\Message\UploadedFileInterface instance for the given location in the tree.

The tree structure referenced should mimic the naming structure in which files were submitted.

In the simplest example, this might be a single named form element submitted as:

  1. <input type="file" name="avatar" />

In this case, the structure in $_FILES would look like:

  1. array(
  2. 'avatar' => array(
  3. 'tmp_name' => 'phpUxcOty',
  4. 'name' => 'my-avatar.png',
  5. 'size' => 90996,
  6. 'type' => 'image/png',
  7. 'error' => 0,
  8. ),
  9. )

The normalized form returned by getUploadedFiles() would be:

  1. array(
  2. 'avatar' => /* UploadedFileInterface instance */
  3. )

In the case of an input using array notation for the name:

  1. <input type="file" name="my-form[details][avatar]" />

$_FILES ends up looking like this:

  1. array(
  2. 'my-form' => array(
  3. 'details' => array(
  4. 'avatar' => array(
  5. 'tmp_name' => 'phpUxcOty',
  6. 'name' => 'my-avatar.png',
  7. 'size' => 90996,
  8. 'type' => 'image/png',
  9. 'error' => 0,
  10. ),
  11. ),
  12. ),
  13. )

And the corresponding tree returned by getUploadedFiles() should be:

  1. array(
  2. 'my-form' => array(
  3. 'details' => array(
  4. 'avatar' => /* UploadedFileInterface instance */
  5. ),
  6. ),
  7. )

In some cases, you may specify an array of files:

  1. Upload an avatar: <input type="file" name="my-form[details][avatars][]" />
  2. Upload an avatar: <input type="file" name="my-form[details][avatars][]" />

(As an example, JavaScript controls might spawn additional file upload inputs to allow uploading multiple files at once.)

In such a case, the specification implementation must aggregate all information related to the file at the given index. The reason is because $_FILES deviates from its normal structure in such cases:

  1. array(
  2. 'my-form' => array(
  3. 'details' => array(
  4. 'avatars' => array(
  5. 'tmp_name' => array(
  6. 0 => '...',
  7. 1 => '...',
  8. 2 => '...',
  9. ),
  10. 'name' => array(
  11. 0 => '...',
  12. 1 => '...',
  13. 2 => '...',
  14. ),
  15. 'size' => array(
  16. 0 => '...',
  17. 1 => '...',
  18. 2 => '...',
  19. ),
  20. 'type' => array(
  21. 0 => '...',
  22. 1 => '...',
  23. 2 => '...',
  24. ),
  25. 'error' => array(
  26. 0 => '...',
  27. 1 => '...',
  28. 2 => '...',
  29. ),
  30. ),
  31. ),
  32. ),
  33. )

The above $_FILES array would correspond to the following structure as returned by getUploadedFiles():

  1. array(
  2. 'my-form' => array(
  3. 'details' => array(
  4. 'avatars' => array(
  5. 0 => /* UploadedFileInterface instance */,
  6. 1 => /* UploadedFileInterface instance */,
  7. 2 => /* UploadedFileInterface instance */,
  8. ),
  9. ),
  10. ),
  11. )

Consumers would access index 1 of the nested array using:

  1. $request->getUploadedFiles()['my-form']['details']['avatars'][1];

Because the uploaded files data is derivative (derived from $_FILES or the request body), a mutator method, withUploadedFiles(), is also present in the interface, allowing delegation of the normalization to another process.

In the case of the original examples, consumption resembles the following:

  1. $file0 = $request->getUploadedFiles()['files'][0];
  2. $file1 = $request->getUploadedFiles()['files'][1];
  3. printf(
  4. "Received the files %s and %s",
  5. $file0->getClientFilename(),
  6. $file1->getClientFilename()
  7. );
  8. // "Received the files file0.txt and file1.html"

This proposal also recognizes that implementations may operate in non-SAPI environments. As such, UploadedFileInterface provides methods for ensuring operations will work regardless of environment. In particular:

  • moveTo($targetPath) is provided as a safe and recommended alternative to calling move_uploaded_file() directly on the temporary upload file. Implementations will detect the correct operation to use based on environment.
  • getStream() will return a StreamInterface instance. In non-SAPI environments, one proposed possibility is to parse individual upload files into php://temp streams instead of directly to files; in such cases, no upload file is present. getStream() is therefore guaranteed to work regardless of environment.

As examples:

  1. // Move a file to an upload directory
  2. $filename = sprintf(
  3. '%s.%s',
  4. create_uuid(),
  5. pathinfo($file0->getClientFilename(), PATHINFO_EXTENSION)
  6. );
  7. $file0->moveTo(DATA_DIR . '/' . $filename);
  8. // Stream a file to Amazon S3.
  9. // Assume $s3wrapper is a PHP stream that will write to S3, and that
  10. // Psr7StreamWrapper is a class that will decorate a StreamInterface as a PHP
  11. // StreamWrapper.
  12. $stream = new Psr7StreamWrapper($file1->getStream());
  13. stream_copy_to_stream($stream, $s3wrapper);

2. Package

上面讨论的接口和类库已经整合成为扩展包: psr/http-message

3. Interfaces

3.1 Psr\Http\Message\MessageInterface

  1. <?php
  2. namespace Psr\Http\Message;
  3. /**
  4. *
  5. * HTTP 消息值得是客户端发起的「请求」和服务器端返回的「响应」,此接口
  6. * 定义了他们通用的方法。
  7. *
  8. * HTTP 消息是被视为无法修改的,所有能修改状态的方法,都 **必须** 有一套
  9. * 机制,在内部保持好原有的内容,然后把修改状态后的信息返回。
  10. *
  11. * @see http://www.ietf.org/rfc/rfc7230.txt
  12. * @see http://www.ietf.org/rfc/rfc7231.txt
  13. */
  14. interface MessageInterface
  15. {
  16. /**
  17. * 获取字符串形式的 HTTP 协议版本信息
  18. *
  19. * 字符串必须包含 HTTP 版本数字,如:"1.1", "1.0"。
  20. *
  21. * @return string HTTP 协议版本
  22. */
  23. public function getProtocolVersion();
  24. /**
  25. * 返回指定 HTTP 版本号的消息实例。
  26. *
  27. * 传参的版本号必须 **只** 包含 HTTP 版本数字,如:"1.1", "1.0"。
  28. *
  29. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息对象,然后返回
  30. * 一个新的带有传参进去的 HTTP 版本的实例
  31. *
  32. * @param string $version HTTP 版本信息
  33. * @return self
  34. */
  35. public function withProtocolVersion($version);
  36. /**
  37. * 获取所有的头信息
  38. *
  39. * 返回的二维数组中,第一维数组的「键」代表单条头信息的名字,「值」是
  40. * 以数据形式返回的,见以下实例:
  41. *
  42. * // 把「值」的数据当成字串打印出来
  43. * foreach ($message->getHeaders() as $name => $values) {
  44. * echo $name . ': ' . implode(', ', $values);
  45. * }
  46. *
  47. * // 迭代的循环二维数组
  48. * foreach ($message->getHeaders() as $name => $values) {
  49. * foreach ($values as $value) {
  50. * header(sprintf('%s: %s', $name, $value), false);
  51. * }
  52. * }
  53. *
  54. * 虽然头信息是没有大小写之分,但是使用 `getHeaders()` 会返回保留了原本
  55. * 大小写形式的内容。
  56. *
  57. * @return string[][] 返回一个两维数组,第一维数组的「键」 **必须** 为单条头信息的
  58. * 名称,对应的是由字串组成的数组,请注意,对应的「值」 **必须** 是数组形式的。
  59. */
  60. public function getHeaders();
  61. /**
  62. * 检查是否头信息中包含有此名称的值,不区分大小写
  63. *
  64. * @param string $name 不区分大小写的头信息名称
  65. * @return bool 找到返回 true,未找到返回 false
  66. */
  67. public function hasHeader($name);
  68. /**
  69. * 根据给定的名称,获取一条头信息,不区分大小写,以数组形式返回
  70. *
  71. * 此方法以数组形式返回对应名称的头信息。
  72. *
  73. * 如果没有对应的头信息,**必须** 返回一个空数组。
  74. *
  75. * @param string $name 不区分大小写的头部字段名称。
  76. * @return string[] 返回头信息中,对应名称的,由字符串组成的数组值,如果没有对应
  77. * 的内容,**必须** 返回空数组。
  78. */
  79. public function getHeader($name);
  80. /**
  81. * 根据给定的名称,获取一条头信息,不区分大小写,以逗号分隔的形式返回
  82. *
  83. * 此方法返回所有对应的头信息,并将其使用逗号分隔的方法拼接起来。
  84. *
  85. * 注意:不是所有的头信息都可使用逗号分隔的方法来拼接,对于那些头信息,请使用
  86. * `getHeader()` 方法来获取。
  87. *
  88. * 如果没有对应的头信息,此方法 **必须** 返回一个空字符串。
  89. *
  90. * @param string $name 不区分大小写的头部字段名称。
  91. * @return string 返回头信息中,对应名称的,由逗号分隔组成的字串,如果没有对应
  92. * 的内容,**必须** 返回空字符串。
  93. */
  94. public function getHeaderLine($name);
  95. /**
  96. * 返回指定头信息「键/值」对的消息实例。
  97. *
  98. * 虽然头信息是不区分大小写的,但是此方法必须保留其传参时的大小写状态,并能够在
  99. * 调用 `getHeaders()` 的时候被取出。
  100. *
  101. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息对象,然后返回
  102. * 一个新的带有传参进去头信息的实例
  103. *
  104. * @param string $name Case-insensitive header field name.
  105. * @param string|string[] $value Header value(s).
  106. * @return self
  107. * @throws \InvalidArgumentException for invalid header names or values.
  108. */
  109. public function withHeader($name, $value);
  110. /**
  111. * 返回一个头信息增量的 HTTP 消息实例。
  112. *
  113. * 原有的头信息会被保留,新的值会作为增量加上,如果头信息不存在的话,会被加上。
  114. *
  115. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息对象,然后返回
  116. * 一个新的修改过的 HTTP 消息实例。
  117. *
  118. * @param string $name 不区分大小写的头部字段名称。
  119. * @param string|string[] $value 头信息对应的值。
  120. * @return self
  121. * @throws \InvalidArgumentException 头信息字段名称非法时会被抛出。
  122. * @throws \InvalidArgumentException 头信息的值非法的时候,会被抛出。
  123. */
  124. public function withAddedHeader($name, $value);
  125. /**
  126. * 返回被移除掉指定头信息的 HTTP 消息实例。
  127. *
  128. * 头信息字段在解析的时候,**必须** 保证是不区分大小写的。
  129. *
  130. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息对象,然后返回
  131. * 一个新的修改过的 HTTP 消息实例。
  132. *
  133. * @param string $name 不区分大小写的头部字段名称。
  134. * @return self
  135. */
  136. public function withoutHeader($name);
  137. /**
  138. * 获取 HTTP 消息的内容。
  139. *
  140. * @return StreamInterface 以数据流的形式返回。
  141. */
  142. public function getBody();
  143. /**
  144. * 返回拼接了内容的 HTTP 消息实例。
  145. *
  146. * 内容 **必须** 是 StreamInterface 接口的实例。
  147. *
  148. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息对象,然后返回
  149. * 一个新的修改过的 HTTP 消息实例。
  150. *
  151. * @param StreamInterface $body 数据流形式的内容。
  152. * @return self
  153. * @throws \InvalidArgumentException 当消息内容不正确的时候。
  154. */
  155. public function withBody(StreamInterface $body);
  156. }

3.2 Psr\Http\Message\RequestInterface

  1. <?php
  2. namespace Psr\Http\Message;
  3. /**
  4. * 代表客户端请求的 HTTP 消息对象。
  5. *
  6. * 根据规范,每一个 HTTP 请求都包含以下信息:
  7. *
  8. * - HTTP 协议版本号 (Protocol version)
  9. * - HTTP 请求方法 (HTTP method)
  10. * - URI
  11. * - 头信息 (Headers)
  12. * - 消息内容 (Message body)
  13. *
  14. * 在构造 HTTP 请求对象的时候,实现类库 **必须** 从给出的 URI 中去提取 HOST 信息。
  15. *
  16. * HTTP 请求是被视为无法修改的,所有能修改状态的方法,都 **必须** 有一套机制,在内部保
  17. * 持好原有的内容,然后把修改状态后的,新的 HTTP 请求实例返回。
  18. */
  19. interface RequestInterface extends MessageInterface
  20. {
  21. /**
  22. * 获取消息请求的目标。
  23. *
  24. * 在大部分情况下,此方法会返回完整的 URI,除非 `withRequestTarget()` 被设置过。
  25. *
  26. * 如果没有提供 URI,并且没有提供任何的请求目标,此方法 **必须** 返回 "/"。
  27. *
  28. * @return string
  29. */
  30. public function getRequestTarget();
  31. /**
  32. * 返回一个指定目标的请求实例。
  33. *
  34. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 请求实例,然后返回
  35. * 一个新的修改过的 HTTP 请求实例。
  36. *
  37. * @see 关于请求目标的各种允许的格式,请见 http://tools.ietf.org/html/rfc7230#section-2.7
  38. *
  39. * @param mixed $requestTarget
  40. * @return self
  41. */
  42. public function withRequestTarget($requestTarget);
  43. /**
  44. * 获取当前请求使用的 HTTP 方法
  45. *
  46. * @return string HTTP 方法字符串
  47. */
  48. public function getMethod();
  49. /**
  50. * 返回更改了请求方法的消息实例。
  51. *
  52. * 虽然,在大部分情况下,HTTP 请求方法都是使用大写字母来标示的,但是,实现类库 **一定不可**
  53. * 修改用户传参的大小格式。
  54. *
  55. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 请求实例,然后返回
  56. * 一个新的修改过的 HTTP 请求实例。
  57. *
  58. * @param string $method 大小写敏感的方法名
  59. * @return self
  60. * @throws \InvalidArgumentException 当非法的 HTTP 方法名传入时会抛出异常。
  61. */
  62. public function withMethod($method);
  63. /**
  64. * 获取 URI 实例。
  65. *
  66. * 此方法必须返回 `UriInterface` 的 URI 实例。
  67. *
  68. * @see http://tools.ietf.org/html/rfc3986#section-4.3
  69. * @return UriInterface 返回与当前请求相关 `UriInterface` 类型的 URI 实例。
  70. */
  71. public function getUri();
  72. /**
  73. * 返回修改了 URI 的消息实例。
  74. *
  75. * 当传入的 `URI` 包含有 `HOST` 信息时,**必须** 更新 `HOST` 头信息,如果 `URI`
  76. * 实例没有附带 `HOST` 信息,任何之前存在的 `HOST` 信息 **必须** 作为候补,应用
  77. * 更改到返回的消息实例里。
  78. *
  79. * 你可以通过传入第二个参数来,来干预方法的处理,当 `$preserveHost` 设置为 `true`
  80. * 的时候,会保留原来的 `HOST` 信息。
  81. *
  82. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 请求实例,然后返回
  83. * 一个新的修改过的 HTTP 请求实例。
  84. *
  85. * @see http://tools.ietf.org/html/rfc3986#section-4.3
  86. * @param UriInterface $uri `UriInterface` 类型的 URI 实例
  87. * @param bool $preserveHost 是否保留原有的 HOST 头信息
  88. * @return self
  89. */
  90. public function withUri(UriInterface $uri, $preserveHost = false);
  91. }

3.2.1 Psr\Http\Message\ServerRequestInterface

  1. <?php
  2. namespace Psr\Http\Message;
  3. /**
  4. * Representation of an incoming, server-side HTTP request.
  5. *
  6. * Per the HTTP specification, this interface includes properties for
  7. * each of the following:
  8. *
  9. * - Protocol version
  10. * - HTTP method
  11. * - URI
  12. * - Headers
  13. * - Message body
  14. *
  15. * Additionally, it encapsulates all data as it has arrived to the
  16. * application from the CGI and/or PHP environment, including:
  17. *
  18. * - The values represented in $_SERVER.
  19. * - Any cookies provided (generally via $_COOKIE)
  20. * - Query string arguments (generally via $_GET, or as parsed via parse_str())
  21. * - Upload files, if any (as represented by $_FILES)
  22. * - Deserialized body parameters (generally from $_POST)
  23. *
  24. * $_SERVER values MUST be treated as immutable, as they represent application
  25. * state at the time of request; as such, no methods are provided to allow
  26. * modification of those values. The other values provide such methods, as they
  27. * can be restored from $_SERVER or the request body, and may need treatment
  28. * during the application (e.g., body parameters may be deserialized based on
  29. * content type).
  30. *
  31. * Additionally, this interface recognizes the utility of introspecting a
  32. * request to derive and match additional parameters (e.g., via URI path
  33. * matching, decrypting cookie values, deserializing non-form-encoded body
  34. * content, matching authorization headers to users, etc). These parameters
  35. * are stored in an "attributes" property.
  36. *
  37. * HTTP 请求是被视为无法修改的,所有能修改状态的方法,都 **必须** 有一套机制,在内部保
  38. * 持好原有的内容,然后把修改状态后的,新的 HTTP 请求实例返回。
  39. */
  40. interface ServerRequestInterface extends RequestInterface
  41. {
  42. /**
  43. * Retrieve server parameters.
  44. *
  45. * Retrieves data related to the incoming request environment,
  46. * typically derived from PHP's $_SERVER superglobal. The data IS NOT
  47. * REQUIRED to originate from $_SERVER.
  48. *
  49. * @return array
  50. */
  51. public function getServerParams();
  52. /**
  53. * Retrieve cookies.
  54. *
  55. * Retrieves cookies sent by the client to the server.
  56. *
  57. * The data MUST be compatible with the structure of the $_COOKIE
  58. * superglobal.
  59. *
  60. * @return array
  61. */
  62. public function getCookieParams();
  63. /**
  64. * Return an instance with the specified cookies.
  65. *
  66. * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST
  67. * be compatible with the structure of $_COOKIE. Typically, this data will
  68. * be injected at instantiation.
  69. *
  70. * This method MUST NOT update the related Cookie header of the request
  71. * instance, nor related values in the server params.
  72. *
  73. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息实例,然后返回
  74. * 一个新的修改过的 HTTP 消息实例。
  75. *
  76. * @param array $cookies Array of key/value pairs representing cookies.
  77. * @return self
  78. */
  79. public function withCookieParams(array $cookies);
  80. /**
  81. * Retrieve query string arguments.
  82. *
  83. * Retrieves the deserialized query string arguments, if any.
  84. *
  85. * Note: the query params might not be in sync with the URI or server
  86. * params. If you need to ensure you are only getting the original
  87. * values, you may need to parse the query string from `getUri()->getQuery()`
  88. * or from the `QUERY_STRING` server param.
  89. *
  90. * @return array
  91. */
  92. public function getQueryParams();
  93. /**
  94. * Return an instance with the specified query string arguments.
  95. *
  96. * These values SHOULD remain immutable over the course of the incoming
  97. * request. They MAY be injected during instantiation, such as from PHP's
  98. * $_GET superglobal, or MAY be derived from some other value such as the
  99. * URI. In cases where the arguments are parsed from the URI, the data
  100. * MUST be compatible with what PHP's parse_str() would return for
  101. * purposes of how duplicate query parameters are handled, and how nested
  102. * sets are handled.
  103. *
  104. * Setting query string arguments MUST NOT change the URI stored by the
  105. * request, nor the values in the server params.
  106. *
  107. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息实例,然后返回
  108. * 一个新的修改过的 HTTP 消息实例。
  109. *
  110. * @param array $query Array of query string arguments, typically from
  111. * $_GET.
  112. * @return self
  113. */
  114. public function withQueryParams(array $query);
  115. /**
  116. * Retrieve normalized file upload data.
  117. *
  118. * This method returns upload metadata in a normalized tree, with each leaf
  119. * an instance of Psr\Http\Message\UploadedFileInterface.
  120. *
  121. * These values MAY be prepared from $_FILES or the message body during
  122. * instantiation, or MAY be injected via withUploadedFiles().
  123. *
  124. * @return array An array tree of UploadedFileInterface instances; an empty
  125. * array MUST be returned if no data is present.
  126. */
  127. public function getUploadedFiles();
  128. /**
  129. * Create a new instance with the specified uploaded files.
  130. *
  131. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息实例,然后返回
  132. * 一个新的修改过的 HTTP 消息实例。
  133. *
  134. * @param array An array tree of UploadedFileInterface instances.
  135. * @return self
  136. * @throws \InvalidArgumentException if an invalid structure is provided.
  137. */
  138. public function withUploadedFiles(array $uploadedFiles);
  139. /**
  140. * Retrieve any parameters provided in the request body.
  141. *
  142. * If the request Content-Type is either application/x-www-form-urlencoded
  143. * or multipart/form-data, and the request method is POST, this method MUST
  144. * return the contents of $_POST.
  145. *
  146. * Otherwise, this method may return any results of deserializing
  147. * the request body content; as parsing returns structured content, the
  148. * potential types MUST be arrays or objects only. A null value indicates
  149. * the absence of body content.
  150. *
  151. * @return null|array|object The deserialized body parameters, if any.
  152. * These will typically be an array or object.
  153. */
  154. public function getParsedBody();
  155. /**
  156. * Return an instance with the specified body parameters.
  157. *
  158. * These MAY be injected during instantiation.
  159. *
  160. * If the request Content-Type is either application/x-www-form-urlencoded
  161. * or multipart/form-data, and the request method is POST, use this method
  162. * ONLY to inject the contents of $_POST.
  163. *
  164. * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of
  165. * deserializing the request body content. Deserialization/parsing returns
  166. * structured data, and, as such, this method ONLY accepts arrays or objects,
  167. * or a null value if nothing was available to parse.
  168. *
  169. * As an example, if content negotiation determines that the request data
  170. * is a JSON payload, this method could be used to create a request
  171. * instance with the deserialized parameters.
  172. *
  173. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息实例,然后返回
  174. * 一个新的修改过的 HTTP 消息实例。
  175. *
  176. * @param null|array|object $data The deserialized body data. This will
  177. * typically be in an array or object.
  178. * @return self
  179. * @throws \InvalidArgumentException if an unsupported argument type is
  180. * provided.
  181. */
  182. public function withParsedBody($data);
  183. /**
  184. * Retrieve attributes derived from the request.
  185. *
  186. * The request "attributes" may be used to allow injection of any
  187. * parameters derived from the request: e.g., the results of path
  188. * match operations; the results of decrypting cookies; the results of
  189. * deserializing non-form-encoded message bodies; etc. Attributes
  190. * will be application and request specific, and CAN be mutable.
  191. *
  192. * @return mixed[] Attributes derived from the request.
  193. */
  194. public function getAttributes();
  195. /**
  196. * Retrieve a single derived request attribute.
  197. *
  198. * Retrieves a single derived request attribute as described in
  199. * getAttributes(). If the attribute has not been previously set, returns
  200. * the default value as provided.
  201. *
  202. * This method obviates the need for a hasAttribute() method, as it allows
  203. * specifying a default value to return if the attribute is not found.
  204. *
  205. * @see getAttributes()
  206. * @param string $name The attribute name.
  207. * @param mixed $default Default value to return if the attribute does not exist.
  208. * @return mixed
  209. */
  210. public function getAttribute($name, $default = null);
  211. /**
  212. * Return an instance with the specified derived request attribute.
  213. *
  214. * This method allows setting a single derived request attribute as
  215. * described in getAttributes().
  216. *
  217. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息实例,然后返回
  218. * 一个新的修改过的 HTTP 消息实例。
  219. *
  220. * @see getAttributes()
  221. * @param string $name The attribute name.
  222. * @param mixed $value The value of the attribute.
  223. * @return self
  224. */
  225. public function withAttribute($name, $value);
  226. /**
  227. * Return an instance that removes the specified derived request attribute.
  228. *
  229. * This method allows removing a single derived request attribute as
  230. * described in getAttributes().
  231. *
  232. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息实例,然后返回
  233. * 一个新的修改过的 HTTP 消息实例。
  234. *
  235. * @see getAttributes()
  236. * @param string $name The attribute name.
  237. * @return self
  238. */
  239. public function withoutAttribute($name);
  240. }

3.3 Psr\Http\Message\ResponseInterface

  1. <?php
  2. namespace Psr\Http\Message;
  3. /**
  4. * Representation of an outgoing, server-side response.
  5. *
  6. * Per the HTTP specification, this interface includes properties for
  7. * each of the following:
  8. *
  9. * - Protocol version
  10. * - Status code and reason phrase
  11. * - Headers
  12. * - Message body
  13. *
  14. * Responses are considered immutable; all methods that might change state MUST
  15. * be implemented such that they retain the internal state of the current
  16. * message and return an instance that contains the changed state.
  17. *
  18. * HTTP 响应是被视为无法修改的,所有能修改状态的方法,都 **必须** 有一套机制,在内部保
  19. * 持好原有的内容,然后把修改状态后的,新的 HTTP 响应实例返回。
  20. */
  21. interface ResponseInterface extends MessageInterface
  22. {
  23. /**
  24. * Gets the response status code.
  25. *
  26. * The status code is a 3-digit integer result code of the server's attempt
  27. * to understand and satisfy the request.
  28. *
  29. * @return int Status code.
  30. */
  31. public function getStatusCode();
  32. /**
  33. * Return an instance with the specified status code and, optionally, reason phrase.
  34. *
  35. * If no reason phrase is specified, implementations MAY choose to default
  36. * to the RFC 7231 or IANA recommended reason phrase for the response's
  37. * status code.
  38. *
  39. * 此方法在实现的时候,**必须** 保留原有的不可修改的 HTTP 消息实例,然后返回
  40. * 一个新的修改过的 HTTP 消息实例。
  41. *
  42. * @see http://tools.ietf.org/html/rfc7231#section-6
  43. * @see http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  44. * @param int $code The 3-digit integer result code to set.
  45. * @param string $reasonPhrase The reason phrase to use with the
  46. * provided status code; if none is provided, implementations MAY
  47. * use the defaults as suggested in the HTTP specification.
  48. * @return self
  49. * @throws \InvalidArgumentException For invalid status code arguments.
  50. */
  51. public function withStatus($code, $reasonPhrase = '');
  52. /**
  53. * Gets the response reason phrase associated with the status code.
  54. *
  55. * Because a reason phrase is not a required element in a response
  56. * status line, the reason phrase value MAY be empty. Implementations MAY
  57. * choose to return the default RFC 7231 recommended reason phrase (or those
  58. * listed in the IANA HTTP Status Code Registry) for the response's
  59. * status code.
  60. *
  61. * @see http://tools.ietf.org/html/rfc7231#section-6
  62. * @see http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  63. * @return string Reason phrase; must return an empty string if none present.
  64. */
  65. public function getReasonPhrase();
  66. }

3.4 Psr\Http\Message\StreamInterface

  1. <?php
  2. namespace Psr\Http\Message;
  3. /**
  4. * Describes a data stream.
  5. *
  6. * Typically, an instance will wrap a PHP stream; this interface provides
  7. * a wrapper around the most common operations, including serialization of
  8. * the entire stream to a string.
  9. */
  10. interface StreamInterface
  11. {
  12. /**
  13. * Reads all data from the stream into a string, from the beginning to end.
  14. *
  15. * This method MUST attempt to seek to the beginning of the stream before
  16. * reading data and read the stream until the end is reached.
  17. *
  18. * Warning: This could attempt to load a large amount of data into memory.
  19. *
  20. * This method MUST NOT raise an exception in order to conform with PHP's
  21. * string casting operations.
  22. *
  23. * @see http://php.net/manual/en/language.oop5.magic.php#object.tostring
  24. * @return string
  25. */
  26. public function __toString();
  27. /**
  28. * Closes the stream and any underlying resources.
  29. *
  30. * @return void
  31. */
  32. public function close();
  33. /**
  34. * Separates any underlying resources from the stream.
  35. *
  36. * After the stream has been detached, the stream is in an unusable state.
  37. *
  38. * @return resource|null Underlying PHP stream, if any
  39. */
  40. public function detach();
  41. /**
  42. * Get the size of the stream if known.
  43. *
  44. * @return int|null Returns the size in bytes if known, or null if unknown.
  45. */
  46. public function getSize();
  47. /**
  48. * Returns the current position of the file read/write pointer
  49. *
  50. * @return int Position of the file pointer
  51. * @throws \RuntimeException on error.
  52. */
  53. public function tell();
  54. /**
  55. * Returns true if the stream is at the end of the stream.
  56. *
  57. * @return bool
  58. */
  59. public function eof();
  60. /**
  61. * Returns whether or not the stream is seekable.
  62. *
  63. * @return bool
  64. */
  65. public function isSeekable();
  66. /**
  67. * Seek to a position in the stream.
  68. *
  69. * @see http://www.php.net/manual/en/function.fseek.php
  70. * @param int $offset Stream offset
  71. * @param int $whence Specifies how the cursor position will be calculated
  72. * based on the seek offset. Valid values are identical to the built-in
  73. * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
  74. * offset bytes SEEK_CUR: Set position to current location plus offset
  75. * SEEK_END: Set position to end-of-stream plus offset.
  76. * @throws \RuntimeException on failure.
  77. */
  78. public function seek($offset, $whence = SEEK_SET);
  79. /**
  80. * Seek to the beginning of the stream.
  81. *
  82. * If the stream is not seekable, this method will raise an exception;
  83. * otherwise, it will perform a seek(0).
  84. *
  85. * @see seek()
  86. * @see http://www.php.net/manual/en/function.fseek.php
  87. * @throws \RuntimeException on failure.
  88. */
  89. public function rewind();
  90. /**
  91. * Returns whether or not the stream is writable.
  92. *
  93. * @return bool
  94. */
  95. public function isWritable();
  96. /**
  97. * Write data to the stream.
  98. *
  99. * @param string $string The string that is to be written.
  100. * @return int Returns the number of bytes written to the stream.
  101. * @throws \RuntimeException on failure.
  102. */
  103. public function write($string);
  104. /**
  105. * Returns whether or not the stream is readable.
  106. *
  107. * @return bool
  108. */
  109. public function isReadable();
  110. /**
  111. * Read data from the stream.
  112. *
  113. * @param int $length Read up to $length bytes from the object and return
  114. * them. Fewer than $length bytes may be returned if underlying stream
  115. * call returns fewer bytes.
  116. * @return string Returns the data read from the stream, or an empty string
  117. * if no bytes are available.
  118. * @throws \RuntimeException if an error occurs.
  119. */
  120. public function read($length);
  121. /**
  122. * Returns the remaining contents in a string
  123. *
  124. * @return string
  125. * @throws \RuntimeException if unable to read.
  126. * @throws \RuntimeException if error occurs while reading.
  127. */
  128. public function getContents();
  129. /**
  130. * Get stream metadata as an associative array or retrieve a specific key.
  131. *
  132. * The keys returned are identical to the keys returned from PHP's
  133. * stream_get_meta_data() function.
  134. *
  135. * @see http://php.net/manual/en/function.stream-get-meta-data.php
  136. * @param string $key Specific metadata to retrieve.
  137. * @return array|mixed|null Returns an associative array if no key is
  138. * provided. Returns a specific key value if a key is provided and the
  139. * value is found, or null if the key is not found.
  140. */
  141. public function getMetadata($key = null);
  142. }

3.5 Psr\Http\Message\UriInterface

  1. <?php
  2. namespace Psr\Http\Message;
  3. /**
  4. * URI 数据对象。
  5. *
  6. * 此接口按照 RFC 3986 来构建 HTTP URI,提供了一些通用的操作,你可以自由的对此接口
  7. * 进行扩展。你可以使用此 URI 接口来做 HTTP 相关的操作,也可以使用此接口做任何 URI
  8. * 相关的操作。
  9. *
  10. * 此接口的实例化对象被视为无法修改的,所有能修改状态的方法,都 **必须** 有一套机制,在内部保
  11. * 持好原有的内容,然后把修改状态后的,新的实例返回。
  12. *
  13. * @see http://tools.ietf.org/html/rfc3986 (URI 通用标准规范)
  14. */
  15. interface UriInterface
  16. {
  17. /**
  18. * 从 URI 中取出 scheme。
  19. *
  20. * 如果不存在 Scheme,此方法 **必须** 返回空字符串。
  21. *
  22. * 返回的数据 **必须** 是小写字母,遵照 RFC 3986 规范 3.1 章节。
  23. *
  24. * 最后部分的 ":" 字串不属于 Scheme,**一定不可** 作为返回数据的一部分。
  25. *
  26. * @see https://tools.ietf.org/html/rfc3986#section-3.1
  27. * @return string URI scheme 的值
  28. */
  29. public function getScheme();
  30. /**
  31. * 返回 URI 授权信息。
  32. *
  33. * 如果没有 URI 信息的话,**必须** 返回一个空数组。
  34. *
  35. * URI 的授权信息语法是:
  36. *
  37. * <pre>
  38. * [user-info@]host[:port]
  39. * </pre>
  40. *
  41. * 如果端口部分没有设置,或者端口不是标准端口,**一定不可** 包含在返回值内。
  42. *
  43. * @see https://tools.ietf.org/html/rfc3986#section-3.2
  44. * @return string URI 授权信息,格式为:"[user-info@]host[:port]"
  45. */
  46. public function getAuthority();
  47. /**
  48. * 从 URI 中获取用户信息。
  49. *
  50. * 如果不存在用户信息,此方法 **必须** 返回一个空字符串。
  51. *
  52. * 用户信息后面跟着的 "@" 字符,不是用户信息里面的一部分,**一定不可** 在返回值里
  53. * 出现。
  54. *
  55. * @return string URI 的用户信息,格式:"username[:password]"
  56. */
  57. public function getUserInfo();
  58. /**
  59. * 从 URI 信息中获取 HOST 值。
  60. *
  61. * 如果 URI 中没有此值,**必须** 返回空字符串。
  62. *
  63. * 返回的数据 **必须** 是小写字母,遵照 RFC 3986 规范 3.2.2 章节。
  64. *
  65. * @see http://tools.ietf.org/html/rfc3986#section-3.2.2
  66. * @return string URI 信息中的 HOST 值。
  67. */
  68. public function getHost();
  69. /**
  70. * 从 URI 信息中获取端口信息。
  71. *
  72. * 如果端口信息是与当前 Scheme 的标准端口不匹配的话,就使用整数值的格式返回,如果是一
  73. * 样的话,**必须** 返回 `null` 值。
  74. *
  75. * 如果存在端口信息,都是不存在 scheme 信息的话,**必须** 返回 `null` 值。
  76. *
  77. * 如果不存在端口数据,但是 scheme 数据存在的话,**可以** 返回 scheme 对应的
  78. * 标准端口,但是 **应该** 返回 `null`。
  79. *
  80. * @return null|int 从 URI 信息中的端口信息。
  81. */
  82. public function getPort();
  83. /**
  84. * 从 URI 信息中获取路径。
  85. *
  86. * The path can either be empty or absolute (starting with a slash) or
  87. * rootless (not starting with a slash). Implementations MUST support all
  88. * three syntaxes.
  89. *
  90. * Normally, the empty path "" and absolute path "/" are considered equal as
  91. * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically
  92. * do this normalization because in contexts with a trimmed base path, e.g.
  93. * the front controller, this difference becomes significant. It's the task
  94. * of the user to handle both "" and "/".
  95. *
  96. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  97. * any characters. To determine what characters to encode, please refer to
  98. * RFC 3986, Sections 2 and 3.3.
  99. *
  100. * As an example, if the value should include a slash ("/") not intended as
  101. * delimiter between path segments, that value MUST be passed in encoded
  102. * form (e.g., "%2F") to the instance.
  103. *
  104. * @see https://tools.ietf.org/html/rfc3986#section-2
  105. * @see https://tools.ietf.org/html/rfc3986#section-3.3
  106. * @return string The URI path.
  107. */
  108. public function getPath();
  109. /**
  110. * Retrieve the query string of the URI.
  111. *
  112. * If no query string is present, this method MUST return an empty string.
  113. *
  114. * The leading "?" character is not part of the query and MUST NOT be
  115. * added.
  116. *
  117. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  118. * any characters. To determine what characters to encode, please refer to
  119. * RFC 3986, Sections 2 and 3.4.
  120. *
  121. * As an example, if a value in a key/value pair of the query string should
  122. * include an ampersand ("&") not intended as a delimiter between values,
  123. * that value MUST be passed in encoded form (e.g., "%26") to the instance.
  124. *
  125. * @see https://tools.ietf.org/html/rfc3986#section-2
  126. * @see https://tools.ietf.org/html/rfc3986#section-3.4
  127. * @return string The URI query string.
  128. */
  129. public function getQuery();
  130. /**
  131. * Retrieve the fragment component of the URI.
  132. *
  133. * If no fragment is present, this method MUST return an empty string.
  134. *
  135. * The leading "#" character is not part of the fragment and MUST NOT be
  136. * added.
  137. *
  138. * The value returned MUST be percent-encoded, but MUST NOT double-encode
  139. * any characters. To determine what characters to encode, please refer to
  140. * RFC 3986, Sections 2 and 3.5.
  141. *
  142. * @see https://tools.ietf.org/html/rfc3986#section-2
  143. * @see https://tools.ietf.org/html/rfc3986#section-3.5
  144. * @return string The URI fragment.
  145. */
  146. public function getFragment();
  147. /**
  148. * Return an instance with the specified scheme.
  149. *
  150. * This method MUST retain the state of the current instance, and return
  151. * an instance that contains the specified scheme.
  152. *
  153. * Implementations MUST support the schemes "http" and "https" case
  154. * insensitively, and MAY accommodate other schemes if required.
  155. *
  156. * An empty scheme is equivalent to removing the scheme.
  157. *
  158. * @param string $scheme The scheme to use with the new instance.
  159. * @return self A new instance with the specified scheme.
  160. * @throws \InvalidArgumentException for invalid schemes.
  161. * @throws \InvalidArgumentException for unsupported schemes.
  162. */
  163. public function withScheme($scheme);
  164. /**
  165. * Return an instance with the specified user information.
  166. *
  167. * This method MUST retain the state of the current instance, and return
  168. * an instance that contains the specified user information.
  169. *
  170. * Password is optional, but the user information MUST include the
  171. * user; an empty string for the user is equivalent to removing user
  172. * information.
  173. *
  174. * @param string $user The user name to use for authority.
  175. * @param null|string $password The password associated with $user.
  176. * @return self A new instance with the specified user information.
  177. */
  178. public function withUserInfo($user, $password = null);
  179. /**
  180. * Return an instance with the specified host.
  181. *
  182. * This method MUST retain the state of the current instance, and return
  183. * an instance that contains the specified host.
  184. *
  185. * An empty host value is equivalent to removing the host.
  186. *
  187. * @param string $host The hostname to use with the new instance.
  188. * @return self A new instance with the specified host.
  189. * @throws \InvalidArgumentException for invalid hostnames.
  190. */
  191. public function withHost($host);
  192. /**
  193. * Return an instance with the specified port.
  194. *
  195. * This method MUST retain the state of the current instance, and return
  196. * an instance that contains the specified port.
  197. *
  198. * Implementations MUST raise an exception for ports outside the
  199. * established TCP and UDP port ranges.
  200. *
  201. * A null value provided for the port is equivalent to removing the port
  202. * information.
  203. *
  204. * @param null|int $port The port to use with the new instance; a null value
  205. * removes the port information.
  206. * @return self A new instance with the specified port.
  207. * @throws \InvalidArgumentException for invalid ports.
  208. */
  209. public function withPort($port);
  210. /**
  211. * Return an instance with the specified path.
  212. *
  213. * This method MUST retain the state of the current instance, and return
  214. * an instance that contains the specified path.
  215. *
  216. * The path can either be empty or absolute (starting with a slash) or
  217. * rootless (not starting with a slash). Implementations MUST support all
  218. * three syntaxes.
  219. *
  220. * If an HTTP path is intended to be host-relative rather than path-relative
  221. * then it must begin with a slash ("/"). HTTP paths not starting with a slash
  222. * are assumed to be relative to some base path known to the application or
  223. * consumer.
  224. *
  225. * Users can provide both encoded and decoded path characters.
  226. * Implementations ensure the correct encoding as outlined in getPath().
  227. *
  228. * @param string $path The path to use with the new instance.
  229. * @return self A new instance with the specified path.
  230. * @throws \InvalidArgumentException for invalid paths.
  231. */
  232. public function withPath($path);
  233. /**
  234. * Return an instance with the specified query string.
  235. *
  236. * This method MUST retain the state of the current instance, and return
  237. * an instance that contains the specified query string.
  238. *
  239. * Users can provide both encoded and decoded query characters.
  240. * Implementations ensure the correct encoding as outlined in getQuery().
  241. *
  242. * An empty query string value is equivalent to removing the query string.
  243. *
  244. * @param string $query The query string to use with the new instance.
  245. * @return self A new instance with the specified query string.
  246. * @throws \InvalidArgumentException for invalid query strings.
  247. */
  248. public function withQuery($query);
  249. /**
  250. * Return an instance with the specified URI fragment.
  251. *
  252. * This method MUST retain the state of the current instance, and return
  253. * an instance that contains the specified URI fragment.
  254. *
  255. * Users can provide both encoded and decoded fragment characters.
  256. * Implementations ensure the correct encoding as outlined in getFragment().
  257. *
  258. * An empty fragment value is equivalent to removing the fragment.
  259. *
  260. * @param string $fragment The fragment to use with the new instance.
  261. * @return self A new instance with the specified fragment.
  262. */
  263. public function withFragment($fragment);
  264. /**
  265. * Return the string representation as a URI reference.
  266. *
  267. * Depending on which components of the URI are present, the resulting
  268. * string is either a full URI or relative reference according to RFC 3986,
  269. * Section 4.1. The method concatenates the various components of the URI,
  270. * using the appropriate delimiters:
  271. *
  272. * - If a scheme is present, it MUST be suffixed by ":".
  273. * - If an authority is present, it MUST be prefixed by "//".
  274. * - The path can be concatenated without delimiters. But there are two
  275. * cases where the path has to be adjusted to make the URI reference
  276. * valid as PHP does not allow to throw an exception in __toString():
  277. * - If the path is rootless and an authority is present, the path MUST
  278. * be prefixed by "/".
  279. * - If the path is starting with more than one "/" and no authority is
  280. * present, the starting slashes MUST be reduced to one.
  281. * - If a query is present, it MUST be prefixed by "?".
  282. * - If a fragment is present, it MUST be prefixed by "#".
  283. *
  284. * @see http://tools.ietf.org/html/rfc3986#section-4.1
  285. * @return string
  286. */
  287. public function __toString();
  288. }

3.6 Psr\Http\Message\UploadedFileInterface

  1. <?php
  2. namespace Psr\Http\Message;
  3. /**
  4. * 通过 HTTP 请求上传的一个文件内容。
  5. *
  6. * 此接口的实例是被视为无法修改的,所有能修改状态的方法,都 **必须** 有一套机制,在内部保
  7. * 持好原有的内容,然后把修改状态后的,新的实例返回。
  8. */
  9. interface UploadedFileInterface
  10. {
  11. /**
  12. * 获取上传文件的数据流。
  13. *
  14. * 此方法必须返回一个 `StreamInterface` 实例,此方法的目的在于允许 PHP 对获取到的数
  15. * 据流直接操作,如 stream_copy_to_stream() 。
  16. *
  17. * 如果在调用此方法之前调用了 `moveTo()` 方法,此方法 **必须** 抛出异常。
  18. *
  19. * @return StreamInterface 上传文件的数据流
  20. * @throws \RuntimeException 没有数据流的情形下。
  21. * @throws \RuntimeException 无法创建数据流。
  22. */
  23. public function getStream();
  24. /**
  25. * 把上传的文件移动到新目录。
  26. *
  27. * 此方法保证能同时在 `SAPI` 和 `non-SAPI` 环境下使用。实现类库 **必须** 判断
  28. * 当前处在什么环境下,并且使用合适的方法来处理,如 move_uploaded_file(), rename()
  29. * 或者数据流操作。
  30. *
  31. * $targetPath 可以是相对路径,也可以是绝对路径,使用 rename() 解析起来应该是一样的。
  32. *
  33. * 当这一次完成后,原来的文件 **必须** 会被移除。
  34. *
  35. * 如果此方法被调用多次,一次以后的其他调用,都要抛出异常。
  36. *
  37. * 如果在 SAPI 环境下的话,$_FILES 内有值,当使用 moveTo(), is_uploaded_file()
  38. * 和 move_uploaded_file() 方法来移动文件时 **应该** 确保权限和上传状态的准确性。
  39. *
  40. * 如果你希望操作数据流的话,请使用 `getStream()` 方法,因为在 SAPI 场景下,无法
  41. * 保证书写入数据流目标。
  42. *
  43. * @see http://php.net/is_uploaded_file
  44. * @see http://php.net/move_uploaded_file
  45. * @param string $targetPath 目标文件路径。
  46. * @throws \InvalidArgumentException 参数有问题时抛出异常。
  47. * @throws \RuntimeException 发生任何错误,都抛出此异常。
  48. * @throws \RuntimeException 多次运行,也抛出此异常。
  49. */
  50. public function moveTo($targetPath);
  51. /**
  52. * 获取文件大小。
  53. *
  54. * 实现类库 **应该** 优先使用 $_FILES 里的 `size` 数值。
  55. *
  56. * @return int|null 以 bytes 为单位,或者 null 未知的情况下。
  57. */
  58. public function getSize();
  59. /**
  60. * 获取上传文件时出现的错误。
  61. *
  62. * 返回值 **必须** 是 PHP 的 UPLOAD_ERR_XXX 常量。
  63. *
  64. * 如果文件上传成功,此方法 **必须** 返回 UPLOAD_ERR_OK。
  65. *
  66. * 实现类库 **必须** 返回 $_FILES 数组中的 `error` 值。
  67. *
  68. * @see http://php.net/manual/en/features.file-upload.errors.php
  69. * @return int PHP 的 UPLOAD_ERR_XXX 常量。
  70. */
  71. public function getError();
  72. /**
  73. * 获取客户端上传的文件的名称。
  74. *
  75. * 永远不要信任此方法返回的数据,客户端有可能发送了一个恶意的文件名来攻击你的程序。
  76. *
  77. * 实现类库 **应该** 返回存储在 $_FILES 数组中 `name` 的值。
  78. *
  79. * @return string|null 用户上传的名字,或者 null 如果没有此值。
  80. */
  81. public function getClientFilename();
  82. /**
  83. * 客户端提交的文件类型。
  84. *
  85. * 永远不要信任此方法返回的数据,客户端有可能发送了一个恶意的文件类型名称来攻击你的程序。
  86. *
  87. * 实现类库 **应该** 返回存储在 $_FILES 数组中 `type` 的值。
  88. *
  89. * @return string|null 用户上传的类型,或者 null 如果没有此值。
  90. */
  91. public function getClientMediaType();
  92. }