Weave Code
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

Http Factory Implementations Laravel Package

psr-discovery/http-factory-implementations

Discovers a PSR-17 HTTP factory at runtime by scanning for well-known implementations and returning the first available instance. Ideal for libraries/SDKs that want PSR-17 support without hard dependencies or user configuration. PHP 8.2+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package in your Laravel project (preferably as a dev dependency):

    composer require --dev psr-discovery/http-factory-implementations
    
  2. Ensure a PSR-17 implementation is available (e.g., nyholm/psr7 or guzzlehttp/psr7):

    composer require nyholm/psr7
    
  3. First use case: Instantiating a PSR-17 factory in a Laravel service:

    use PsrDiscovery\Discover;
    
    $requestFactory = Discover::httpRequestFactory();
    $request = $requestFactory->createRequest('GET', '/api/users');
    

Where to Look First

  • Discover facade: Central entry point for all PSR-17 factories.
  • Laravel Service Providers: Ideal place to initialize and bind factories.
  • Test classes: Leverage mocking priority for seamless testing.

Implementation Patterns

Core Workflow

  1. Dependency Injection: Bind discovered factories in a service provider:

    public function register()
    {
        $this->app->singleton(\Psr\Http\Message\RequestFactoryInterface::class,
            fn() => Discover::httpRequestFactory(singleton: true));
    }
    
  2. HTTP Client Integration: Use with Laravel HTTP clients (e.g., Guzzle) or SDKs:

    $client = new \GuzzleHttp\Client([
        'handler' => \Http\Discovery\Psr18ClientDiscovery::find(),
        'request_factory' => Discover::httpRequestFactory(),
    ]);
    
  3. Testing: Mock factories automatically in tests (no manual setup):

    public function testApiRequest()
    {
        $requestFactory = Discover::httpRequestFactory();
        $request = $requestFactory->createRequest('POST', '/login');
        // Test logic...
    }
    

Integration Tips

  • Laravel HTTP Middleware: Use factories to create PSR-7 messages:
    public function handle($request, Closure $next)
    {
        $psrRequest = Discover::httpRequestFactory()->createRequest(
            $request->method(),
            $request->url()
        );
        // ...
    }
    
  • File Uploads: Handle UploadedFileFactoryInterface for file uploads:
    $uploadedFileFactory = Discover::httpUploadedFileFactory();
    $uploadedFile = $uploadedFileFactory->createUploadedFile(
        '/path/to/file', 'filename.txt', 'text/plain', 1024, UPLOAD_ERR_OK
    );
    
  • URI Handling: Use UriFactoryInterface for URI manipulation:
    $uriFactory = Discover::httpUriFactory();
    $uri = $uriFactory->createUri('https://example.com/api');
    

Gotchas and Tips

Pitfalls

  1. Null Returns:

    • Always check for null when no implementation is found:
      $factory = Discover::httpRequestFactory();
      if (!$factory) {
          throw new \RuntimeException('No PSR-17 factory available');
      }
      
    • Fix: Ensure a PSR-17 implementation is installed (e.g., nyholm/psr7).
  2. Mocking Overrides:

    • Mock implementations take priority in tests. To force a real implementation:
      Discover::httpRequestFactory(); // Uses mock if available
      Discover::httpRequestFactory(singleton: true); // May bypass mocks
      
  3. Singleton Behavior:

    • Singleton mode (singleton: true) caches the first discovered instance. Use sparingly in tests to avoid side effects.

Debugging

  • Verify Installed Implementations: Check composer.json for PSR-17 packages (e.g., nyholm/psr7, guzzlehttp/psr7).
  • Log Discovery: Add debug logs to trace which implementation is selected:
    \PsrDiscovery\Implementations\Psr17\RequestFactories::prefer('nyholm/psr7');
    $factory = Discover::httpRequestFactory(); // Logs selected class
    

Extension Points

  1. Custom Implementations: Extend the discovery list by modifying the package’s Implementations class or submitting a PR to the upstream repo.

  2. Conditional Discovery: Override discovery logic in a service provider:

    Discover::httpRequestFactory(); // Default behavior
    // OR
    $factory = new \Nyholm\Psr7\Factory\Psr17Factory(); // Hardcoded
    
  3. Performance: Cache discovered factories in Laravel’s cache:

    $factory = cache()->remember('psr17.request_factory', 3600, fn() =>
        Discover::httpRequestFactory(singleton: true)
    );
    

Laravel-Specific Tips

  • Service Container Binding: Bind factories to Laravel’s container for seamless DI:
    $this->app->bind(\Psr\Http\Message\RequestFactoryInterface::class,
        fn() => Discover::httpRequestFactory()
    );
    
  • Testing: Use Laravel’s RefreshDatabase or MigrateFresh traits alongside mock factories for isolated tests.
  • Configuration: Store preferred implementations in config/services.php:
    'psr17' => [
        'request_factory' => 'nyholm/psr7',
    ],
    
    Then access via:
    config('services.psr17.request_factory');
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor