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 Laravel Package

tuupola/http-factory

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require tuupola/http-factory
    

    The package auto-discovers HTTP factories via Laravel's service provider system—no manual configuration is required.

  2. First Use Case: Creating an HTTP Client

    use Tuupola\Http\Factory;
    
    $client = Factory::createClient();
    

    This leverages Laravel's default HTTP client (Guzzle by default) unless overridden.

  3. Where to Look First

    • Service Provider: config/http-factory.php (if customization is needed).
    • Factory Class: Tuupola\Http\Factory (core methods: createClient(), createStream(), createUri()).
    • PSR-17 Compliance: The package implements HttpClientFactoryInterface, StreamFactoryInterface, and UriFactoryInterface.

Implementation Patterns

Core Workflows

  1. PSR-17 Factory Integration Use the factory to create PSR-17 compliant objects (e.g., Uri, Stream, HttpClient) for consistency across Laravel apps:

    $uri = Factory::createUri('https://example.com');
    $stream = Factory::createStream(fopen('php://memory', 'r+'));
    $client = Factory::createClient(['timeout' => 5.0]);
    
  2. Dependency Injection Bind the factory to Laravel's container in AppServiceProvider for reusable access:

    $this->app->singleton(\Tuupola\Http\Factory::class, function ($app) {
        return new \Tuupola\Http\Factory();
    });
    

    Then inject via constructor:

    public function __construct(private Factory $factory) {}
    
  3. Custom Factories Extend the factory to support custom implementations (e.g., a mock HTTP client for testing):

    class CustomFactory extends \Tuupola\Http\Factory {
        public function createClient(array $config = []): HttpClientInterface {
            return new MockHttpClient(); // Custom implementation
        }
    }
    
  4. Dynamic Configuration Override default configurations via config/http-factory.php:

    'default' => [
        'client' => [
            'timeout' => 10.0,
            'headers' => ['User-Agent' => 'MyApp/1.0'],
        ],
    ],
    

Integration Tips

  • API Clients: Use Factory::createClient() to standardize HTTP client creation across services.
  • Testing: Replace the default client with a mock in tests:
    $this->app->bind(\Tuupola\Http\Factory::class, function () {
        return new CustomFactory(); // Mock factory
    });
    
  • Middleware: Attach middleware to the client dynamically:
    $client = Factory::createClient();
    $client->getEmitter()->attach(
        new \GuzzleHttp\Middleware::retry(RetryMiddleware::defaults())
    );
    

Gotchas and Tips

Pitfalls

  1. Auto-Discovery Conflicts If multiple packages implement HttpClientFactoryInterface, the last registered factory wins. Explicitly bind your factory to avoid surprises:

    $this->app->bind(\Tuupola\Http\Factory::class, function () {
        return new \Tuupola\Http\Factory();
    });
    
  2. Stream Handling The createStream() method returns a Psr\Http\Message\StreamInterface, not a native PHP stream. Ensure compatibility when passing streams to non-PSR-17 code:

    $stream = Factory::createStream(fopen('file.txt', 'r'));
    if (!$stream instanceof \Psr\Http\Message\StreamInterface) {
        throw new \RuntimeException('Stream is not PSR-17 compliant');
    }
    
  3. Configuration Overrides Config values in config/http-factory.php are merged with runtime arguments. Runtime args take precedence:

    $client = Factory::createClient(['timeout' => 2.0]); // Overrides config
    

Debugging

  • Factory Instantiation Issues If Factory::createClient() fails, check:

    • Laravel's service container bindings.
    • The HttpClientFactoryInterface implementation (e.g., Guzzle's Client).
    • Custom factory extensions for errors.
  • Stream Resource Leaks Always close streams explicitly or use context managers:

    $stream = Factory::createStream(fopen('file.txt', 'r'));
    try {
        // Use stream
    } finally {
        $stream->close();
    }
    

Extension Points

  1. Custom Factories Override methods like createUri() or createStream() in a subclass:

    class CustomFactory extends \Tuupola\Http\Factory {
        public function createUri(string $uri = '', array $parts = []): UriInterface {
            return new \Laminas\Diactoros\Uri($uri); // Use Laminas instead of default
        }
    }
    
  2. Dynamic Factory Resolution Use Laravel's resolve() method to dynamically switch factories:

    $factory = app()->make(\Tuupola\Http\Factory::class, ['config' => 'custom']);
    
  3. Testing Utilities Create a test helper to reset the factory:

    function mockHttpFactory() {
        $this->app->bind(\Tuupola\Http\Factory::class, function () {
            return new CustomFactory(); // Reset to mock
        });
    }
    
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.
terminal42/code-quality-tools
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