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

Connection Manager Extra Laravel Package

clue/connection-manager-extra

Extra connector decorators for ReactPHP Socket. Wrap ConnectorInterface to add retries, timeouts, delays, rejection rules, swapping, consecutive/random selection, concurrency limits and selective routing—without changing your async connect() code.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require clue/connection-manager-extra
    
  2. Require ReactPHP's Socket (dependency):
    composer require react/socket
    
  3. Basic usage with a decorator:
    use React\Socket\Connector;
    use ConnectionManager\Extra\ConnectionManagerTimeout;
    
    $connector = new Connector();
    $timeoutConnector = new ConnectionManagerTimeout($connector, 5.0); // 5-second timeout
    
    $timeoutConnector->connect('example.com:80')
        ->then(function ($stream) {
            $stream->write("GET / HTTP/1.0\r\nHost: example.com\r\n\r\n");
            $stream->end();
        })
        ->otherwise(function ($exception) {
            echo "Connection failed: " . $exception->getMessage();
        });
    

First Use Case: Retry Mechanism

Use ConnectionManagerRepeat to retry failed connections:

$retryConnector = new ConnectionManagerRepeat($connector, 3); // 3 total attempts
$retryConnector->connect('unreliable.example.com:80')->then(...);

Implementation Patterns

Decorator Stacking

Combine decorators for complex workflows:

$baseConnector = new Connector();
$delayedConnector = new ConnectionManagerDelay($baseConnector, 1.0); // 1s delay
$retryConnector = new ConnectionManagerRepeat($delayedConnector, 3); // 3 retries
$timeoutConnector = new ConnectionManagerTimeout($retryConnector, 10.0); // 10s timeout

Selective Routing (Firewall/ACL)

Route connections based on host/port patterns:

$blocked = new ConnectionManagerReject('Blocked');
$delayed = new ConnectionManagerDelay($connector, 2.0);
$selective = new ConnectionManagerSelective([
    'ads.example.com' => $blocked,
    '*.example.com:80' => $delayed,
    '*' => $connector // Default fallback
]);

Concurrent Fallback

Try multiple connectors in parallel:

$connector1 = new ConnectionManagerTimeout($baseConnector, 2.0);
$connector2 = new ConnectionManagerDelay($baseConnector, 0.5);
$concurrent = new ConnectionManagerConcurrent([$connector1, $connector2]);

Dynamic Swapping

Replace connectors at runtime (e.g., for failover):

$swappable = new ConnectionManagerSwappable($connector);
$swappable->setConnectionManager($newConnector); // Swap during execution

Gotchas and Tips

Debugging Connection Issues

  • Timeouts: Ensure $timeout values are realistic for your network (e.g., 5s for local, 10s+ for remote).
  • Retries: Log failures between retries to debug intermittent issues:
    $retryConnector = new ConnectionManagerRepeat($connector, 3);
    $retryConnector->connect('...')->otherwise(function ($e) {
        \Log::error("Connection failed: " . $e->getMessage());
    });
    

Selective Matching Quirks

  • Wildcards: *.example.com matches sub.example.com but not example.com. Use example.com + *.example.com for full coverage.
  • Port Ranges: Use min-max (e.g., *:80-81) for port ranges. Invalid formats throw InvalidArgumentException.
  • URI Scheme: The package ignores schemes (e.g., http:// or https://) when matching hosts.

Performance Tips

  • Concurrent vs. Consecutive: ConnectionManagerConcurrent is faster but uses more resources. Prefer Consecutive for sequential fallbacks.
  • Loop Handling: Decorators like Timeout/Delay now auto-detect the default loop (PHP 8.1+). Explicitly pass $loop only if needed.

Extension Points

  • Custom Rejection Logic: Override ConnectionManagerReject to implement dynamic blocking (e.g., API-based blacklists).
  • Composite Decorators: Chain decorators for reusable patterns (e.g., RetryWithDelayTimeout).
  • Event Loop Integration: Use ConnectionManagerSwappable to dynamically switch connectors based on runtime conditions (e.g., load balancing).

Common Pitfalls

  1. Infinite Retries: Forgetting to set a timeout on ConnectionManagerRepeat can cause hangs.
  2. Port Matching: *:80 matches example.com:80 but not example.com:443. Use explicit rules for HTTPS.
  3. Loop Conflicts: Mixing decorators with explicit $loop arguments may cause race conditions. Stick to one loop per application.
  4. Resource Leaks: Always call $stream->close() or $stream->end() to avoid memory leaks in long-running connections.

Laravel-Specific Tips

  • Event Loop: Use React\EventLoop\Factory::create() once and reuse it across decorators:
    $loop = React\EventLoop\Factory::create();
    $connector = new Connector($loop);
    
  • Service Container: Bind decorators as singletons in AppServiceProvider:
    $this->app->singleton('retry.connector', function ($app) {
        return new ConnectionManagerRepeat($app['socket.connector'], 3);
    });
    
  • Async Queues: Combine with spatie/async or reactphp/async for non-blocking Laravel jobs:
    use React\Async\AsyncJob;
    
    AsyncJob::perform(function () use ($connector) {
        return $connector->connect('...')->then(...);
    });
    
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