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

Socket Client Laravel Package

php-http/socket-client

PSR-7/PSR-18 HTTP client built on PHP streams. Supports TCP and UNIX domain sockets, TLS/SSL encryption, and client certificates. Lightweight, dependency-minimal option for making HTTP requests via socket connections.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require php-http/socket-client
    

    Ensure php-http/httplug and php-http/client-common are also installed (dependencies).

  2. First Use Case: Create a basic HTTP client using the socket client:

    use Http\Client\Common\PluginClient;
    use Http\Client\Common\Plugin\BaseUriPlugin;
    use Http\Client\Common\Plugin\HeaderAppendPlugin;
    use Http\Client\Socket\Client;
    use Http\Message\MessageFactory\GuzzleMessageFactory;
    
    $client = new Client(
        new GuzzleMessageFactory(),
        ['scheme' => 'http', 'host' => 'example.com', 'port' => 80]
    );
    
    $pluginClient = new PluginClient($client);
    $pluginClient->addPlugin(new BaseUriPlugin('https://example.com'));
    $pluginClient->addPlugin(new HeaderAppendPlugin('Accept', 'application/json'));
    
    $response = $pluginClient->get('/api/endpoint');
    echo $response->getBody();
    
  3. Where to Look First:

    • Documentation (if available).
    • src/Client.php for core functionality.
    • tests/ for usage examples and edge cases.

Implementation Patterns

Common Workflows

  1. Plugin-Based Extensibility: Use plugins to modify requests/responses globally (e.g., auth, retries, logging):

    $client = new PluginClient(new Client($messageFactory, $socketConfig));
    $client->addPlugin(new AuthPlugin('Bearer', 'token123'));
    
  2. Connection Pooling: Reuse the client instance for multiple requests (sockets are connectionless by default, but plugins like Http\Client\Common\Plugin\PoolPlugin can optimize):

    $client = new Client($messageFactory, ['host' => 'api.example.com']);
    $client->sendRequest(new Request('GET', '/data'));
    $client->sendRequest(new Request('POST', '/data', [], '{"key":"value"}'));
    
  3. Async-Like Behavior: While not truly async, chain requests with callbacks for sequential processing:

    $response1 = $client->get('/user/1');
    $userId = json_decode($response1->getBody(), true)['id'];
    $response2 = $client->get("/user/{$userId}/posts");
    
  4. Custom Socket Configuration: Override defaults (e.g., timeout, SSL):

    $client = new Client($messageFactory, [
        'host' => 'secure.example.com',
        'port' => 443,
        'ssl' => [
            'verify_peer' => true,
            'allow_self_signed' => false,
        ],
        'timeout' => 10.0,
    ]);
    
  5. Integration with Laravel: Bind the client to the container in AppServiceProvider:

    $this->app->singleton('http.client.socket', function () {
        return new PluginClient(new Client(
            new GuzzleMessageFactory(),
            ['host' => config('services.api.host')]
        ));
    });
    

    Use in controllers:

    $response = app('http.client.socket')->get('/endpoint');
    

Gotchas and Tips

Pitfalls

  1. No Built-in Retries: Unlike Guzzle, this client lacks retry logic. Use Http\Client\Common\Plugin\RetryPlugin:

    $client->addPlugin(new RetryPlugin());
    
  2. SSL Certificate Validation: By default, SSL peer verification is enabled. Disable only for testing:

    $client = new Client($messageFactory, [
        'ssl' => ['verify_peer' => false], // ⚠️ Insecure!
    ]);
    
  3. Connection Leaks: Ensure sockets are properly closed (handled automatically in most cases, but debug with stream_socket_shutdown() if issues arise).

  4. Plugin Order Matters: Plugins execute in registration order. Auth plugins should run before BaseUriPlugin:

    $client->addPlugin(new AuthPlugin(...)); // Runs first
    $client->addPlugin(new BaseUriPlugin(...));
    
  5. No Middleware: Unlike Laravel HTTP clients, this uses plugins, not middleware. Convert middleware to plugins if needed.


Debugging Tips

  1. Enable Verbose Logging: Use Http\Client\Common\Plugin\LoggerPlugin with Monolog:

    $logger = new \Monolog\Logger('socket_client');
    $client->addPlugin(new LoggerPlugin($logger, LoggerPlugin::DEBUG));
    
  2. Check Raw Responses: Inspect headers/body for errors:

    $status = $response->getStatusCode();
    $body = $response->getBody();
    $headers = $response->getHeaders();
    
  3. Test Locally: Use localhost with php -S for quick debugging:

    $client = new Client($messageFactory, ['host' => '127.0.0.1', 'port' => 8000]);
    

Extension Points

  1. Custom Message Factories: Extend Http\Message\MessageFactory\MessageFactoryInterface for non-Guzzle messages (e.g., Symfony HTTP).

  2. Socket-Specific Plugins: Create plugins to modify socket options dynamically:

    class TimeoutPlugin implements Plugin {
        public function __invoke(Transfer $transfer): void {
            $transfer->setSocketOption(SOL_SOCKET, SO_RCVTIMEO, ['sec' => 5, 'usec' => 0]);
        }
    }
    
  3. Event Dispatching: Use Http\Client\Common\Plugin\EventPlugin to hook into request/response lifecycle:

    $client->addPlugin(new EventPlugin(function (Event $event) {
        if ($event->isRequest()) {
            $event->getRequest()->setHeader('X-Custom', 'Value');
        }
    }));
    
  4. Proxy Support: Configure via socket options:

    $client = new Client($messageFactory, [
        'proxy' => 'tcp://proxy.example.com:8080',
    ]);
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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