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

Command Launcher Laravel Package

digitalnoise/command-launcher

Laravel package for launching and managing console commands programmatically. Provides a simple API to trigger Artisan commands, pass arguments/options, and handle execution flow for scheduled tasks, integrations, and background processes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require digitalnoise/command-launcher
    

    Register the service provider in config/app.php:

    'providers' => [
        DigitalNoise\CommandLauncher\CommandLauncherServiceProvider::class,
    ],
    
  2. First Command Execution Define and run a simple command in a controller or service:

    use DigitalNoise\CommandLauncher\CommandLauncher;
    
    public function runExampleCommand()
    {
        $launcher = app(CommandLauncher::class);
        $output = $launcher->run('echo "Hello from CLI!"');
        return $output; // Returns the command output
    }
    
  3. Key Configuration Configure timeouts and retries in config/command-launcher.php (if needed):

    'default_timeout' => 30, // seconds
    'max_retries' => 3,
    

Implementation Patterns

Core Workflows

  1. Synchronous Execution Run commands directly in a request lifecycle:

    $launcher = app(CommandLauncher::class);
    $result = $launcher->run('php artisan optimize:clear');
    
  2. Asynchronous Dispatch Offload commands to queues for background processing:

    $launcher->dispatch('php artisan queue:work --once')
             ->onQueue('cli-jobs')
             ->delay(now()->addMinutes(5));
    
  3. Chaining Commands Execute multiple commands sequentially:

    $launcher->run('composer install')
             ->then('php artisan migrate')
             ->then('php artisan optimize');
    
  4. Error Handling Define fallback actions for failed commands:

    $launcher->run('php artisan queue:work --once')
             ->onFailure(function ($command, $output) {
                 Log::error("Command failed: {$command}", ['output' => $output]);
                 // Send notification or retry logic
             });
    

Integration Tips

  • Leverage Laravel’s Service Container Bind the launcher to a custom interface for better testability:

    $this->app->bind(CommandLauncherInterface::class, function ($app) {
        return $app->make(CommandLauncher::class);
    });
    
  • Queue-Based Workflows Extend ShouldQueue for complex CLI jobs:

    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class ProcessMediaJob implements ShouldQueue
    {
        use Queueable;
    
        public function handle()
        {
            app(CommandLauncher::class)->run('ffmpeg -i input.mp4 output.mp4');
        }
    }
    
  • Dynamic Command Building Use Laravel’s Process facade for dynamic commands:

    use Symfony\Component\Process\Process;
    
    $process = new Process(['php', 'artisan', 'command', '--option=value']);
    $launcher->run($process);
    
  • Logging and Monitoring Integrate with Laravel’s logging channels:

    $launcher->run('php artisan command')
             ->setLogger(app(\Psr\Log\LoggerInterface::class));
    

Gotchas and Tips

Pitfalls

  1. Command Injection Risks

    • Issue: Improperly sanitized commands can lead to shell injection.
    • Fix: Use Laravel’s Process facade with predefined command arrays:
      $launcher->run(['php', 'artisan', 'command']); // Safer than strings
      
  2. Blocking Queues

    • Issue: Long-running commands may block queue workers.
    • Fix: Set appropriate timeouts and use dispatchSync() sparingly.
  3. Environment Dependencies

    • Issue: Commands may fail if CLI tools (e.g., ffmpeg) are missing.
    • Fix: Validate dependencies in a CommandNotFoundHandler:
      $launcher->setCommandNotFoundHandler(function ($command) {
          throw new \RuntimeException("Command '{$command}' not found. Install required tools.");
      });
      
  4. Output Handling

    • Issue: Large command outputs may overwhelm logs.
    • Fix: Stream output or truncate logs:
      $launcher->run('command')->setOutputLimit(1024); // Limit to 1KB
      
  5. Retry Logic

    • Issue: Default retries may not handle transient errors well.
    • Fix: Customize retry logic with onRetry():
      $launcher->run('command')
               ->retry(3)
               ->onRetry(function ($attempt, $command) {
                   Log::warning("Retrying command {$command} (attempt {$attempt})");
               });
      

Debugging Tips

  • Inspect Command Outputs Use Laravel’s logging to debug:

    $launcher->run('command')->setLogger(app(\Psr\Log\LoggerInterface::class));
    
  • Simulate Failures Test error handling with forced failures:

    $launcher->run('false-command')->onFailure(function ($command, $output) {
        // Handle failure
    });
    
  • Check Worker Logs Monitor queue workers for timeouts or crashes:

    tail -f storage/logs/laravel.log | grep "CommandLauncher"
    

Extension Points

  1. Custom Command Handlers Extend the launcher to support custom logic:

    $launcher->extend('custom', function ($command) {
        return shell_exec($command); // Or custom logic
    });
    
  2. Plugin System Add plugins for additional features (e.g., Slack notifications):

    $launcher->addPlugin(new SlackNotificationPlugin());
    
  3. Event Listeners Listen to command events (e.g., CommandStarted, CommandFailed):

    event(new CommandStarted($command, $output));
    

Configuration Quirks

  • Timeout Units Timeouts are in seconds by default. Adjust in config:

    'default_timeout' => 60, // 1 minute
    
  • Queue Priorities Use Laravel’s queue priorities for critical commands:

    $launcher->dispatch('command')->onHighPriorityQueue();
    
  • Environment-Specific Commands Override commands per environment:

    if (app()->environment('production')) {
        $launcher->setCommand('deploy', 'deploy:prod');
    }
    

Performance Tips

  • Batch Processing Use Laravel’s batch() for bulk commands:

    $launcher->batch(['command1', 'command2', 'command3'])->run();
    
  • Parallel Execution Offload independent commands to separate workers:

    $launcher->dispatch('command1')->onQueue('high');
    $launcher->dispatch('command2')->onQueue('low');
    
  • Resource Limits Set memory/time limits for commands:

    $launcher->run('command')->setMemoryLimit('128M')->setTimeout(120);
    
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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme