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

Climate Laravel Package

league/climate

League CLImate makes PHP CLI output nicer with easy colored text, formatting, and styled messages. Install via Composer and use simple methods like red() or blue() to print readable, attention-grabbing console output for scripts and command-line tools.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require league/climate
    

    Add to composer.json under require-dev if only for local scripts.

  2. First Use:

    use League\CLImate\CLImate;
    
    $climate = new CLImate();
    $climate->out('Hello, Laravel!')->bold()->green();
    

    Run via CLI:

    php script.php
    
  3. Key Entry Points:

    • Output: $climate->out(), $climate->error(), $climate->success()
    • Interactive: $climate->confirm(), $climate->input(), $climate->checkboxes()
    • Structured: $climate->table(), $climate->progress(), $climate->columns()

First Use Case: Artisan Command Feedback

Replace a basic echo in a Laravel command:

// Before
echo "User created: " . $user->name;

// After
$this->climate->success("User created: {$user->name}")->bold();

Implementation Patterns

Core Workflows

1. Consistent Output Styling

  • Pattern: Chain methods for reusable styles.
    $climate->out('Warning: ')->yellow()->bold()
            ->out('Disk space low!')->reset();
    
  • Laravel Integration: Create a trait for commands:
    trait UsesCLImate {
        protected function climate() {
            return new CLImate();
        }
    }
    

2. Interactive Prompts

  • Pattern: Validate user input with prompts.
    $name = $climate->input('Enter your name', ['required' => true]);
    $confirm = $climate->confirm('Proceed?', false);
    
  • Laravel Use Case: Replace readline() in custom commands with CLImate’s prompts.

3. Progress Tracking

  • Pattern: Dynamic progress bars for async tasks.
    $progress = $climate->progress()->start('Processing...');
    foreach ($items as $item) {
        $progress->advance();
        // Simulate work
        usleep(100000);
    }
    $progress->finish();
    
  • Laravel Use Case: Wrap Artisan::call() with progress bars for batch jobs.

4. Structured Data Output

  • Pattern: Tables for data-heavy CLI tools.
    $climate->table([
        'ID', 'Name', 'Status'
    ], [
        [1, 'John', 'Active'],
        [2, 'Jane', 'Inactive'],
    ]);
    
  • Laravel Use Case: Replace dd() or var_dump() in debug commands with formatted tables.

5. Cross-Platform Compatibility

  • Pattern: Use CLImate’s built-in checks for ANSI/non-ANSI terminals.
    if ($climate->supportsAnsi()) {
        $climate->out('ANSI colors enabled!')->green();
    }
    
  • Laravel Use Case: Ensure CLI tools work on Windows without manual fixes.

Integration Tips

  1. Service Container Binding: Bind CLImate to Laravel’s container for dependency injection:

    $app->singleton(CLImate::class, function () {
        return new CLImate();
    });
    

    Inject into commands:

    public function __construct(protected CLImate $climate) {}
    
  2. Custom Extensions: Extend CLImate for domain-specific methods:

    $climate->extend('userCreated', function ($user) {
        return $this->success("User {$user->name} created!")->bold();
    });
    

    Use in commands:

    $this->climate->userCreated($user);
    
  3. Logging Integration: Use CLImate’s PSR-3 logger for structured CLI logs:

    $logger = new League\CLImate\Logger\Logger($climate);
    $logger->debug('Debug message');
    
  4. Artisan Command Helpers: Create a base command class:

    abstract class ClimateCommand extends Command {
        protected function climate() {
            return new CLImate();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. ANSI Escape Sequences:

    • Issue: Colors/text formatting may not render on non-ANSI terminals (e.g., Windows without ANSI support).
    • Fix: Use $climate->supportsAnsi() to check before applying styles:
      if ($climate->supportsAnsi()) {
          $climate->out('Colored text')->red();
      } else {
          $climate->out('Colored text (fallback)');
      }
      
  2. Terminal Width Detection:

    • Issue: Incorrect width detection can break tables/columns on some systems.
    • Fix: Manually set width if needed:
      $climate->setTerminalWidth(120);
      
  3. Input Validation:

    • Issue: Custom validation rules may not work as expected with input().
    • Fix: Use accept() with regex or callbacks:
      $email = $climate->input('Email', [
          'accept' => '/^[^\s@]+@[^\s@]+\.[^\s@]+$/'
      ]);
      
  4. Progress Bar Redraws:

    • Issue: Progress bars may flicker or redraw unnecessarily.
    • Fix: Use forceRedraw(false) to optimize:
      $progress->forceRedraw(false);
      
  5. Windows-Specific Quirks:

    • Issue: Password input or terminal width may fail on Windows.
    • Fix: Ensure ext-mbstring is installed or use the seld/cli-prompt polyfill.

Debugging Tips

  1. Disable ANSI for Debugging: Force non-ANSI output to test rendering:

    $climate->forceAnsiOff();
    
  2. Log Raw Output: Use buffer() to capture output for debugging:

    $output = $climate->buffer(function () {
        $climate->out('Debug me')->red();
    });
    $climate->out($output);
    
  3. Check for Deprecations: Monitor the changelog for breaking changes (e.g., PHP 8.2+ type juggling fixes).

Extension Points

  1. Custom Output Writers: Override default output behavior by setting a custom writer:

    $climate->output = new CustomWriter();
    
  2. Argument Parsing: Extend argument handling for custom CLI tools:

    $climate->arguments->addOption('verbose', 'v', 'Enable verbose mode');
    $verbose = $climate->arguments->has('verbose');
    
  3. PSR-3 Logger Integration: Use CLImate’s logger with Monolog or other PSR-3 loggers:

    $logger = new League\CLImate\Logger\Logger($climate);
    $logger->addHandler(new StreamHandler('php://stderr', Logger::ERROR));
    
  4. Custom Terminal Objects: Create reusable components (e.g., GitStatus):

    $climate->extend('gitStatus', function () {
        return $this->out('Git: ')->yellow()->out(shell_exec('git status --porcelain'));
    });
    

Laravel-Specific Tips

  1. Artisan Command Styling: Use CLImate in handle() for consistent output:

    public function handle() {
        $this->climate->info('Starting migration...');
        // ...
        $this->climate->success('Migration completed!');
    }
    
  2. Exception Handling: Replace throw new \Exception() with styled errors:

    $this->climate->error('Failed to connect to database!')->bold();
    
  3. Testing CLI Output: Mock CLImate in tests:

    $climate = Mockery::mock(CLImate::class);
    $climate->shouldReceive('out')->with('Expected output');
    $this->app->instance(CLImate::class, $climate);
    
  4. Configuration: Store CLImate settings in config/cli.php:

    'ansi_enabled' => env('CLI_ANSI_ENABLED', true),
    'default_width' => 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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope