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

Manager Laravel Package

graham-campbell/manager

Laravel Manager provides a lightweight base for building driver-based “manager” services in Laravel apps. Supports PHP 7.4–8.5 and Laravel 8–13, offering consistent configuration, driver creation, and resolution patterns for your own integrations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require graham-campbell/manager:^5.3
    
  2. Extend AbstractManager in your package:
    use GrahamCampbell\Manager\AbstractManager;
    
    class MyServiceManager extends AbstractManager
    {
        protected function createConnection(array $config): MyServiceInterface
        {
            return new MyService($config);
        }
    
        protected function getConfigName(): string
        {
            return 'myservice';
        }
    }
    
  3. Register the manager in your package’s service provider:
    $this->app->singleton(MyServiceManager::class, function ($app) {
        return new MyServiceManager($app);
    });
    
  4. Define config in config/myservice.php:
    return [
        'default' => 'driver_name',
        'drivers' => [
            'driver_name' => [
                'key' => 'value',
            ],
        ],
    ];
    

First Use Case

Lazy-load a connection and call methods directly:

$manager = app(MyServiceManager::class);
$manager->methodOnDefaultConnection(); // Dynamic method call
// OR
$connection = $manager->connection('driver_name');
$connection->doSomething();

Implementation Patterns

Core Workflows

  1. Driver-Based Service Resolution

    • Use extend() to dynamically add drivers:
      $manager->extend('custom_driver', function ($app, array $config) {
          return new CustomDriver($config);
      });
      
    • Retrieve connections via connection() (cached) or reconnect() (fresh instance).
  2. Configuration Management

    • Fetch config for a specific connection:
      $config = $manager->getConnectionConfig('driver_name');
      
    • Set/get default connection:
      $manager->setDefaultConnection('driver_name');
      $default = $manager->getDefaultConnection();
      
  3. Dynamic Method Dispatch

    • Call methods on the default connection without explicit retrieval:
      $manager->uploadFile($file); // Delegates to default connection
      
  4. Connection Pooling

    • List all active connections:
      $connections = $manager->getConnections();
      
    • Disconnect explicitly:
      $manager->disconnect('driver_name');
      

Integration Tips

  • Laravel Packages: Use AbstractManager as the base for your package’s service manager (e.g., CacheManager, DatabaseManager).
  • Testing: Mock the manager to test driver-specific logic:
    $manager = Mockery::mock(MyServiceManager::class);
    $manager->shouldReceive('connection')
            ->with('driver_name')
            ->andReturn($mockConnection);
    
  • Configuration: Store driver-specific configs in config/{package}.php under a drivers key.

Gotchas and Tips

Pitfalls

  1. Connection Leaks

    • Issue: Forgetting to call disconnect() can lead to memory leaks if connections are heavyweight (e.g., database, API clients).
    • Fix: Use reconnect() to force a fresh instance when needed.
  2. Dynamic Method Calls

    • Issue: __call may accidentally trigger undefined methods if not guarded.
    • Fix: Override __call in your manager to validate method existence:
      public function __call($method, $parameters)
      {
          if (!method_exists($this->getDefaultConnection(), $method)) {
              throw new BadMethodCallException("Method {$method} does not exist.");
          }
          return call_user_func_array([$this->getDefaultConnection(), $method], $parameters);
      }
      
  3. Config Validation

    • Issue: Missing or invalid config keys may cause silent failures.
    • Fix: Validate config in createConnection():
      if (empty($config['required_key'])) {
          throw new InvalidArgumentException('Config missing required key.');
      }
      
  4. Thread Safety

    • Issue: Connection pools may not be thread-safe in shared environments (e.g., queues).
    • Fix: Use reconnect() or disconnect() before/after queue jobs.

Debugging Tips

  • Check Active Connections:
    dd($manager->getConnections());
    
  • Inspect Config:
    dd($manager->getConnectionConfig('driver_name'));
    
  • Enable Debug Logging: Add a logger to createConnection() to trace driver initialization:
    \Log::debug('Creating connection for driver: ' . $config['driver']);
    

Extension Points

  1. Custom Drivers

    • Register drivers dynamically at runtime:
      $manager->extend('new_driver', function ($app, array $config) {
          return new NewDriver($config);
      });
      
  2. Config Overrides

    • Use getNamedConfig() to fetch config for a specific driver:
      $config = $manager->getNamedConfig('driver_name');
      
  3. Event Hooks

    • Extend the manager to dispatch events (e.g., ConnectionCreated, ConnectionDisconnected):
      protected function createConnection(array $config)
      {
          event(new ConnectionCreating($config));
          $connection = new MyService($config);
          event(new ConnectionCreated($connection));
          return $connection;
      }
      

Performance Tips

  • Lazy Loading: Connections are instantiated only when first accessed, reducing startup overhead.
  • Connection Reuse: The pool avoids recreating connections for repeated calls to connection().
  • Avoid reconnect(): Use sparingly—it bypasses the pool and may duplicate resources.
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.
codraw/graphviz
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata