PSR-7 HTTP Message Interfaces

repository·master·Indexed 27 days ago

https://github.com/php-fig/http-message

Standard interfaces and contracts for HTTP messages in PHP, adhering to the PSR-7 specification. This project defines the core components for compliant implementations, including MessageInterface, RequestInterface, ServerRequestInterface, ResponseInterface, StreamInterface, UriInterface, and UploadedFileInterface. It is not a standalone implementation but a set of contracts that libraries like Guzzle, Laminas Diactoros, or Nyholm PSR-7 must follow.

Tokens
2.7K
Snippets
2
Records
13
Agent score
92%

What's inside php-fig/http-message

  1. Understand the purpose of PSR Http Message

    master

    This repository provides the interfaces, classes, and traits that define the PSR-7 standard for HTTP messages in PHP.

    Important: This repository is not a standalone HTTP message implementation. It defines the interfaces and contracts that an implementation must follow. To actually use HTTP messages in your application, you must use a library that implements these interfaces (such as Guzzle, Laminas Diactoros, or Nyholm PSR-7).

  2. Prepend content to an HTTP body

    master

    Since PSR-7 streams are typically append-only via the write() method, prepending requires a manual process of reading the existing content and rewriting the stream.

    Option 1: Rewriting the stream manually

    1. Get the body stream.
    2. rewind() the stream.
    3. Capture the current contents using getContents().
    4. rewind() the stream again.
    5. write() the new prefix content.
    6. write() the captured original contents.

    Option 2: Using string concatenation

    1. Get the body stream.
    2. rewind() and capture contents as a string.
    3. Concatenate the new prefix to the string.
    4. rewind() the stream.
    5. write() the entire new string.
    // Option 1: Rewriting separately
    $body = $response->getBody();
    $body->rewind();
    $contents = $body->getContents();
    $body->rewind();
    $body->write('ef');
    $body->write($contents);
    
    // Option 2: Using contents as a string
    $body = $response->getBody();
    $body->rewind();
    $contents = $body->getContents();
    $contents = 'ef' . $contents;
    $body->rewind();
    $body->write($contents);
  3. Work with HTTP Message Body

    master

    The body of an HTTP message is handled via a StreamInterface. You can interact with the body either by retrieving the stream object first or by calling methods directly on the message.

    Method 1: Getting the body separately

    This is recommended for multiple operations to avoid repeated calls to getBody(). Since streams are objects, modifications to the stream object affect the message.

    Method 2: Working directly on the message

    Useful for quick, single operations.

    Writing to the body

    Use the write(string $string) method on the stream object to append data to the body.

  4. Work with HTTP Headers

    master

    PSR-7 provides methods to manipulate and inspect headers on both RequestInterface and ResponseInterface objects. Note that most modification methods return a new instance of the message due to the immutability pattern common in PSR-7 implementations.

    Adding and Appending Headers

    • Use withHeader(string $name, string $value) to add a header or replace an existing one.
    • Use withAddedHeader(string $name, string $value) to append a value to an existing header.

    Inspecting Headers

    • Use hasHeader(string $name): bool to check for existence.
    • Use getHeaderLine(string $name): string to get a single string containing all values for the header, separated by commas.
    • Use getHeader(string $name): array to get an array of all values for the header.

    Removing Headers

    • Use withoutHeader(string $name): self to return a new message instance with the specified header removed.
  5. Get body contents from a stream

    master

    To read the full content of an HTTP message body, you must use getContents() on the stream.

    Important: Because streams maintain a pointer, you must call rewind() or seek(0) before calling getContents() if the stream has already been written to or read. If the pointer is at the end of the stream, getContents() will return an empty string.

    $body = $response->getBody();
    $body->rewind(); // or $body->seek(0);
    $bodyText = $body->getContents();
  6. Use StreamInterface methods

    master

    The Psr\Http\Message\StreamInterface describes a data stream used for message bodies.

    Reading and Writing

    • read($length): Read data from the stream.
    • write($string): Write data to the stream.
    • getContents(): Returns the remaining contents in a string.
    • __toString(): Reads all data from the stream into a string from beginning to end.
    • seek($offset, $whence = SEEK_SET): Seek to a position in the stream.
    • rewind(): Seek to the beginning of the stream.
    • eof(): Returns true if the stream is at the end.
    • getSize(): Get the size of the stream if known.
    • isSeekable(): Returns whether or not the stream is seekable.
    • isWritable(): Returns whether or not the stream is writable.
    • isReadable(): Returns whether or not the stream is readable.

    Management

    • close(): Closes the stream and any underlying resources.
    • detach(): Separates any underlying resources from the stream.
    • getMetadata($key = null): Get stream metadata as an associative array or retrieve a specific key.
  7. Use MessageInterface methods

    master

    The Psr\Http\Message\MessageInterface provides methods for managing HTTP protocol versions, headers, and the message body. Note that methods prefixed with with return a new instance of the message.

    Protocol Version

    • getProtocolVersion(): Retrieve HTTP protocol version (e.g., 1.0 or 1.1).
    • withProtocolVersion($version): Returns a new message instance with the given HTTP protocol version.

    Headers

    • getHeaders(): Retrieve all HTTP Headers.
    • hasHeader($name): Checks if an HTTP Header with the given name exists.
    • getHeader($name): Retrieves an array of values for a single header.
    • getHeaderLine($name): Retrieves a comma-separated string of values for a single header.
    • withHeader($name, $value): Returns a new instance with the given header (replaces existing value).
    • withAddedHeader($name, $value): Returns a new instance with the value appended to the header.
    • withoutHeader($name): Removes the HTTP Header with the given name.

    Body

    • getBody(): Retrieves the HTTP Message Body (returns a StreamInterface object).
    • withBody(StreamInterface $body): Returns a new instance with the given HTTP Message Body.
  8. Use RequestInterface methods

    master

    The Psr\Http\Message\RequestInterface extends MessageInterface and adds methods specific to client-side requests.

    Request Target and Method

    • getRequestTarget(): Retrieves the message's request target (e.g., origin-form, absolute-form, authority-form, or asterisk-form).
    • withRequestTarget($requestTarget): Returns a new message instance with the specific request-target.
    • getMethod(): Retrieves the HTTP method (e.g., GET, POST, PUT, DELETE, etc.).
    • withMethod($method): Returns a new message instance with the provided HTTP method.

    URI

    • getUri(): Retrieves the UriInterface instance.
    • withUri(UriInterface $uri, $preserveHost = false): Returns a new message instance with the provided URI.
  9. Use ResponseInterface methods

    master

    The Psr\Http\Message\ResponseInterface extends MessageInterface and adds methods for managing HTTP responses.

    • getStatusCode(): Gets the response status code.
    • withStatus($code, $reasonPhrase = ''): Returns a new response instance with the specified status code and an optional reason phrase.
    • getReasonPhrase(): Gets the response reason phrase associated with the status code.
  10. Use ServerRequestInterface methods

    master

    The Psr\Http\Message\ServerRequestInterface extends RequestInterface and adds methods for handling incoming server-side requests.

    • getServerParams(): Retrieve server parameters (typically derived from $_SERVER).
    • getCookieParams(): Retrieves cookies sent by the client (typically derived from $_COOKIES).
    • withCookieParams(array $cookies): Returns a new request instance with the specified cookies.

    Request Body and Files

    • getParsedBody(): Retrieve any parameters provided in the request body.
    • withParsedBody($data): Returns a new request instance with the specified body parameters.
    • getUploadedFiles(): Retrieve normalized file upload data.
    • withUploadedFiles(array $uploadedFiles): Returns a new request instance with the specified uploaded files.
    • withQueryParams(array $query): Returns a new request instance with the specified query string arguments.

    Attributes

    • getAttributes(): Retrieve attributes derived from the request.
    • getAttribute($name, $default = null): Retrieve a single derived request attribute.
    • withAttribute($name, $value): Returns a new request instance with the specified derived request attribute.
    • withoutAttribute($name): Returns a new request instance without the specified derived request attribute.
  11. Use UriInterface methods

    master

    The Psr\Http\Message\UriInterface is a value object representing a URI.

    Component Accessors

    • getScheme(): Retrieve the scheme component.
    • getAuthority(): Retrieve the authority component.
    • getUserInfo(): Retrieve the user information component.
    • getHost(): Retrieve the host component.
    • getPort(): Retrieve the port component.
    • getPath(): Retrieve the path component.
    • getQuery(): Retrieve the query string.
    • getFragment(): Retrieve the fragment component.

    Component Mutators (Returns new instance)

    • withScheme($scheme)
    • withUserInfo($user, $password = null)
    • withHost($host)
    • withPort($port)
    • withPath($path)
    • withQuery($query)
    • withFragment($fragment)

    String Representation

    • __toString(): Return the string representation as a URI reference.
  12. Use UploadedFileInterface methods

    master

    The Psr\Http\Message\UploadedFileInterface is a value object representing a file uploaded through an HTTP request.

    • getStream(): Retrieve a stream representing the uploaded file.
    • moveTo($targetPath): Move the uploaded file to a new location.
    • getSize(): Retrieve the file size.
    • getError(): Retrieve the error associated with the uploaded file.
    • getClientFilename(): Retrieve the filename sent by the client.
    • getClientMediaType(): Retrieve the media type sent by the client.