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

Cli Laravel Package

21torr/cli

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require 21torr/cli
    

    Ensure Symfony/Console is already in your composer.json (this package wraps it).

  2. Basic Usage Import the Cli facade in your command class:

    use App\Services\Cli;
    
    class MyCommand extends Command
    {
        protected static $defaultName = 'app:my-command';
    
        public function handle()
        {
            $cli = app(Cli::class);
            $cli->info('Hello, Laravel!');
        }
    }
    
  3. First Use Case Replace vanilla Symfony output with styled messages:

    $cli->success('Operation completed!');
    $cli->warning('This might fail.');
    $cli->error('Critical error!');
    

Where to Look First

  • Official Docs (primary reference)
  • src/Helpers/ in the package source for helper methods.
  • tests/ for usage examples and edge cases.

Implementation Patterns

Core Workflows

  1. Styling Output Replace getHelperSet()->get('formatter')->format() with:

    $cli->success('Success message');
    $cli->error('Error message');
    $cli->warning('Warning message');
    $cli->info('Informational message');
    $cli->question('Question? [y/N]');
    
  2. Progress Bars Use the built-in progress bar helper:

    $progress = $cli->progressStart(100);
    for ($i = 0; $i <= 100; $i++) {
        $progress->advance();
    }
    $progress->finish();
    
  3. Tables Render tabular data with auto-formatting:

    $cli->table(['Name', 'Email'], [
        ['John Doe', 'john@example.com'],
        ['Jane Smith', 'jane@example.com'],
    ]);
    
  4. Interactive Prompts Collect user input with validation:

    $name = $cli->ask('What is your name?');
    $confirm = $cli->confirm('Are you sure?', false);
    $password = $cli->secret('Enter password:');
    

Integration Tips

  • Dependency Injection Bind the Cli service in AppServiceProvider for global access:

    $this->app->bind(Cli::class, function ($app) {
        return new Cli($app['symfony.console.style']);
    });
    
  • Command Bootstrapping Extend Command and inject Cli via constructor:

    class MyCommand extends Command
    {
        protected $cli;
    
        public function __construct(Cli $cli)
        {
            $this->cli = $cli;
            parent::__construct();
        }
    }
    
  • Custom Styles Override default styles in config/cli.php:

    'styles' => [
        'success' => ['fg' => 'green', 'options' => ['bold']],
        'error'   => ['fg' => 'red', 'options' => ['bold', 'blink']],
    ],
    
  • Logging Integration Pipe CLI output to Laravel logs:

    $cli->info('Logging this...');
    // Logs to `storage/logs/laravel.log` with `[info]` prefix.
    

Gotchas and Tips

Pitfalls

  1. Style Conflicts

    • If styles (e.g., colors) render incorrectly, ensure your terminal supports ANSI escape codes.
    • Fix: Test in xterm-256color or screen-256color terminals. Fallback to basic styles if needed:
      $cli->setFallbackStyles(true);
      
  2. Progress Bar Freezes

    • Progress bars may hang if the underlying process blocks (e.g., slow DB queries).
    • Fix: Use progressStart() in a separate process or add sleep(0) in loops:
      for ($i = 0; $i < 100; $i++) {
          usleep(1000); // Simulate work
          $progress->advance();
      }
      
  3. Input Buffering

    • secret() may echo input in some terminals (e.g., Windows CMD).
    • Fix: Use symfony/console’s native secret() as a fallback:
      $password = $this->askSecret('Password:');
      
  4. Configuration Overrides

    • Custom config/cli.php may be ignored if cached.
    • Fix: Clear config cache:
      php artisan config:clear
      

Debugging

  • Disable Styles Temporarily disable styles to debug layout issues:

    $cli->disableStyles();
    
  • Log Raw Output Inspect raw output before styling:

    $cli->debug('Raw debug message');
    
  • Check for Deprecations Monitor the changelog for breaking changes in minor updates.

Extension Points

  1. Custom Helpers Extend the Cli class to add domain-specific methods:

    class ExtendedCli extends Cli
    {
        public function logDatabaseStats(array $stats)
        {
            $this->section('Database Stats');
            $this->table(['Metric', 'Value'], $stats);
        }
    }
    
  2. Theme Support Dynamically switch themes based on environment:

    $cli->setTheme(config('app.env') === 'production' ? 'dark' : 'light');
    
  3. Event Listeners Hook into CLI events (e.g., Cli\Events\CommandStarting):

    event(new Cli\Events\CommandStarting($commandName, $input));
    
  4. Localization Override text labels (e.g., "Are you sure?") via language files:

    $cli->setTranslation('confirm', 'Bist du sicher?');
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours