Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Psr17 Laravel Package

loophp/psr17

loophp/psr17 provides a PSR-17 HTTP message factory implementation for PHP, helping you create PSR-7 requests, responses, streams, URIs, and uploaded files in a standards-compliant way. Suitable for libraries and middleware needing PSR factories.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer (now requires PHP 8.1+):

    composer require loophp/psr17:^1.0.6
    

    No additional configuration is required—it remains a drop-in PSR-17 implementation.

  2. First Use Case: HTTP Message Factory Use the Loophp\Psr17\Factory to create PSR-7 HTTP messages (requests/responses) with PSR-17 interfaces:

    use Loophp\Psr17\Factory;
    use Psr\Http\Message\RequestInterface;
    
    $factory = new Factory();
    $request = $factory->createRequest('GET', '/api/users');
    
  3. Where to Look First

    • Factory Class: Core entry point for creating PSR-17-compliant objects.
    • PSR-17 Interfaces: RequestFactoryInterface, ResponseFactoryInterface, StreamFactoryInterface, UriFactoryInterface.
    • Documentation: The PSR-17 spec remains the authoritative reference.
    • PHP Version: Verify your project uses PHP 8.1+ (breaking change in 1.0.6).

Implementation Patterns

Core Workflows

  1. Creating HTTP Messages Use the factory to generate PSR-7 requests/responses with PSR-17 guarantees:

    $response = $factory->createResponse(200)
        ->withHeader('Content-Type', 'application/json')
        ->withBody($factory->createStreamFromString(json_encode(['data' => 'value'])));
    
  2. Stream Handling Convert strings, resources, or files to PSR-17 streams (unchanged):

    $stream = $factory->createStreamFromFile('/path/to/file.txt');
    $stream = $factory->createStreamFromResource(fopen('php://memory', 'r+'));
    
  3. URI Manipulation Build or parse URIs safely (unchanged):

    $uri = $factory->createUri('https://example.com/path?query=value');
    $uri = $uri->withPath('/new-path')->withQuery('new=query');
    
  4. Integration with Middleware/Frameworks Replace Laravel’s default Symfony\Component\HttpFoundation with PSR-17 factories for consistency (unchanged):

    // In a service provider or bootstrap file (PHP 8.1+ required)
    $app->singleton(\Psr\Http\Message\RequestFactoryInterface::class, function ($app) {
        return new Factory();
    });
    

Advanced Patterns

  • Custom Stream Wrappers: Extend Loophp\Psr17\Stream to add custom logic (e.g., compression, logging) (unchanged).
  • Immutable Modifiers: Chain factory methods to build complex messages immutably (unchanged):
    $request = $factory->createRequest('POST', '/submit')
        ->withHeader('X-Custom', 'value')
        ->withBody($factory->createStreamFromString($data));
    

Gotchas and Tips

Pitfalls

  1. PHP Version Requirement (BREAKING) PHP 8.1+ is now mandatory for loophp/psr17:^1.0.6. Projects using PHP < 8.1 must downgrade to ^1.0.5 or later.

  2. No Built-in Caching The factory creates new instances on every call (e.g., createStreamFromString). Cache frequently used streams/URIs if performance is critical (unchanged):

    $cachedStream = $factory->createStreamFromString($data);
    // Reuse $cachedStream instead of recreating.
    
  3. Stream Resource Leaks Ensure streams are detached or closed when no longer needed (unchanged):

    $stream = $factory->createStreamFromFile('/tmp/file');
    $detached = $stream->detach(); // Avoid holding file handles
    
  4. URI Validation The factory validates URIs strictly. Invalid URIs throw exceptions. Sanitize inputs before passing to createUri() (unchanged).

  5. No PSR-17 Server Request/Response This package implements factories only (PSR-17). For full PSR-7 messages, pair with a library like zend-diactoros or nyholm/psr7 (unchanged).

Debugging Tips

  • Inspect Headers/Bodies: Use getHeaders(), getBody()->__toString() to debug messages (unchanged).
  • Stream Position: Check getSize() and tell() to diagnose stream issues (unchanged).
  • URI Components: Break down URIs with getScheme(), getHost(), etc., to isolate problems (unchanged).

Extension Points

  1. Custom Factories Implement your own factories by extending Loophp\Psr17\Factory or individual factory classes (e.g., StreamFactory) (unchanged).

  2. Stream Decorators Wrap streams to add behavior (e.g., logging, gzip) (unchanged):

    use Psr\Http\Message\StreamInterface;
    class LoggingStream implements StreamInterface {
        private StreamInterface $stream;
        public function __construct(StreamInterface $stream) { $this->stream = $stream; }
        public function write($string) { error_log("Writing: $string"); return $this->stream->write($string); }
        // Delegate other methods to $this->stream...
    }
    
  3. Override Defaults Replace the factory globally in Laravel by binding interfaces to your custom implementation (PHP 8.1+ required):

    $this->app->bind(\Psr\Http\Message\RequestFactoryInterface::class, function () {
        return new CustomFactory();
    });
    

Config Quirks

  • No Configuration File: The package is stateless; all behavior is code-driven (unchanged).
  • Thread Safety: Factories and streams are immutable and thread-safe by design (unchanged).
  • PHP 8.1 Features: The refactor may leverage newer PHP features (e.g., named arguments, attributes), but the public API remains unchanged.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
abbasudo/artisan-route
mirvan/ippanel
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource
noith/settings
kda/laravel-package