nyholm/psr7 Documentation
repository·master·Indexed 23 days ago
https://github.com/nyholm/psr7A lightweight, strict, and high-performance PHP implementation of the PSR-7 (HTTP Message Interface) and PSR-17 (HTTP Factories) specifications. It provides concrete implementations for Request, Response, ServerRequest, and Stream, along with the Psr17Factory for creating PSR-7 compliant objects. The library emphasizes immutability and the use of composition over inheritance.
What's inside nyholm/psr7
- You should not extend the classes provided by this library. Instead, use composition or implement the relevant PSR-7 interface yourself. This follows the decorator pattern and ensures better software design and compatibility with the PSR-7 standard.
Create server requests from PHP superglobals
masterTo convert PHP superglobals (like
$_SERVER,$_GET, etc.) into PSR-7 server requests, use thenyholm/psr7-serverpackage. You must provide the necessary factories to theServerRequestCreator.// Requires composer require nyholm/psr7-server $psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory(); $creator = new \Nyholm\Psr7Server\ServerRequestCreator( $psr17Factory, // ServerRequestFactory $psr17Factory, // UriFactory $psr17Factory, // UploadedFileFactory $psr17Factory // StreamFactory ); $serverRequest = $creator->fromGlobals();Mocking PSR-7 classes
masterSince PSR-7 classes are designed as value objects, they can typically be used directly in your tests without the need for mocking. If you encounter a specific scenario that requires a mock, you should mock the interface (e.g.,Psr ing equest-interface) rather than attempting to mock the concrete implementation classes.Install nyholm/psr7 via Composer
masterInstall the lightweight PSR-7 implementation using Composer:
composer require nyholm/psr7Send a request using a PSR-18 client
masterYou can send PSR-7 requests using any PSR-18 compliant HTTP client (such as Buzz). Pass the
Psr17Factoryto the client to handle request creation and compatibility.$psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory(); $psr18Client = new \Buzz\Client\Curl($psr17Factory); $request = $psr17Factory->createRequest('GET', 'http://tnyholm.se'); $response = $psr18Client->sendRequest($request);Emit a PSR-7 response
masterTo send a PSR-7 response to the client (e.g., via SAPI), use an emitter such as
laminas/laminas-httphandlerrunner.// Requires composer require laminas/laminas-httphandlerrunner $psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory(); $responseBody = $psr17Factory->createStream('Hello world'); $response = $psr17Factory->createResponse(200)->withBody($responseBody); (new \Laminas\HttpHandlerRunner\Emitter\SapiEmitter())->emit($response);Create PSR-7 objects using Psr17Factory
masterTo create PSR-7 objects such as requests, streams, and URIs, use the
Nyholm\Psr7\Factory\Psr17Factory. This factory implements the PSR-17 standard, ensuring compatibility with other PSR-compliant libraries.$psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory(); $request = $psr17Factory->createRequest('GET', 'http://tnyholm.se'); $stream = $psr17Factory->createStream('foobar');Create Streams with Psr17Factory
masterThe
Psr17Factoryprovides three ways to create aStreamInterface:createStream(string $content = ''): Creates a stream from a string.createStreamFromFile(string $filename, string $mode = 'r'): Creates a stream from a file. ThrowsRuntimeExceptionif the path is empty or the file cannot be opened, andInvalidArgumentExceptionif the mode is invalid.createStreamFromResource($resource): Creates a stream from an existing PHP resource.
Create a Response with Psr17Factory::createResponse()
masterUse
createResponse()to instantiate a newResponseInterface.- If you provide only the
$code, the$reasonPhrasewill be set tonull(allowing theResponseclass to use its own default logic). - If you provide both
$codeand$reasonPhrase, the response will use the specified phrase.
- If you provide only the
Create new URI instances with 'with' methods
masterSince
UriimplementsUriInterface, it follows the PSR-7 immutability pattern. Methods prefixed withwithdo not modify the existing object; instead, they return a new instance with the specified change. If the new value is identical to the current value, the original instance is returned.Available methods:
withScheme(string $scheme): UriInterfacewithUserInfo(string $user, string $password = null): UriInterfacewithHost(string $host): UriInterfacewithPort(int $port): UriInterfacewithPath(string $path): UriInterfacewithQuery(string $query): UriInterfacewithFragment(string $fragment): UriInterface
Note on Ports: If you set a port that is the default for the current scheme (e.g., 80 for
http), thegetPort()method will returnnullto comply with PSR-7 standards.Instantiate UploadedFile
masterThe
Nyholm\Psr7\UploadedFileclass implementsPsr\Http\Message\UploadedFileInterface. It is used to represent files uploaded via an HTTP request.Constructor Parameters
$streamOrFile: AStreamInterface, a string (path to file), or a PHP resource.$size: An integer representing the file size in bytes.$errorStatus: An integer representing the upload error status. This must be one of the standard PHPUPLOAD_ERR_*constants (e.g.,\UPLOAD_ERR_OK).$clientFilename(optional): A string representing the filename provided by the client.$clientMediaType(optional): A string representing the media type provided by the client.
Error Handling
- If
$errorStatusis not a validUPLOAD_ERR_*constant, an\InvalidArgumentExceptionis thrown. - If
$sizeis not an integer, an\InvalidArgumentExceptionis thrown. - If the provided
$streamOrFileis invalid for the given error status, an\InvalidArgumentExceptionis thrown.
Create a new Response with a different status using withStatus()
masterSince
ResponseimplementsResponseInterface, it follows the PSR-7 immutability pattern. To change the status code, use thewithStatus()method, which returns a new instance of the response with the updated status and reason phrase.Method Signature:
public function withStatus($code, $reasonPhrase = ''): ResponseInterface$code: An integer or string representing the status code. Must be between100and599.$reasonPhrase: An optional string for a custom reason phrase. If empty, the default phrase for the status code is used.
Throws:
\InvalidArgumentExceptionif the status code is not an integer/string or is outside the range100-599.