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

Php Console Color Laravel Package

jakub-onderka/php-console-color

Abandoned PHP library for styling console output with ANSI colors. Formerly used to print colored text in terminals (see example.php). Consider using the maintained alternative: https://github.com/php-parallel-lint/PHP-Console-Color

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require jakub-onderka/php-console-color
    

    (Note: While the package is abandoned, it remains lightweight and functional for basic needs.)

  2. Basic Usage:

    use JakubOnderka\PhpConsoleColor\ConsoleColor;
    
    $color = new ConsoleColor();
    echo $color->getColoredString('Hello, Laravel!', 'green');
    

    (Output: Green text in terminal.)

  3. First Use Case:

    • Logging: Colorize log messages in App\Services\Logger for better readability in CLI tools like laravel-log or monolog.
    • Artisan Commands: Enhance user feedback in Artisan::command() outputs (e.g., success/failure messages).

Implementation Patterns

Core Workflows

  1. Dynamic Styling in Views/Blade:

    // In a Blade template or service
    $color = new ConsoleColor();
    return $color->getColoredString('Warning: ', 'yellow') . 'Database connection failed.';
    

    (Useful for CLI-based admin panels or debug views.)

  2. Conditional Coloring:

    $status = $job->status;
    $color = new ConsoleColor();
    $statusText = $status === 'completed'
        ? $color->getColoredString($status, 'green')
        : $color->getColoredString($status, 'red');
    

    (Apply in App\Jobs\JobStatusChecker or App\Console\Commands\JobMonitor.)

  3. Integration with Laravel’s Logging:

    // In AppServiceProvider::boot()
    $logger = app(\Illuminate\Log\Logger::class);
    $logger->listen(function ($level, $message, array $context) {
        $color = new ConsoleColor();
        echo $color->getColoredString("[{$level}] ", 'cyan') . $message . PHP_EOL;
    });
    

    (Override default log formatting in config/logging.php if needed.)

  4. Artisan Command Feedback:

    // In a custom Artisan command
    $this->info($color->getColoredString('Task completed!', 'green'));
    $this->error($color->getColoredString('Failed to migrate.', 'red'));
    

Advanced Patterns

  • Theming: Create a ConsoleTheme facade to wrap ConsoleColor for consistent styling across the app.
    // app/Facades/ConsoleTheme.php
    public static function warning($text) {
        return (new ConsoleColor())->getColoredString($text, 'yellow');
    }
    
  • ANSI Escape Sequences: For custom ANSI control (e.g., bold/underline), combine with raw escapes:
    echo "\033[1m" . $color->getColoredString('Important!', 'red') . "\033[0m";
    

Gotchas and Tips

Pitfalls

  1. Windows Compatibility:

    • Issue: Colors may not render on older Windows terminals (pre-Windows 10) or in some IDEs (e.g., PhpStorm’s built-in terminal).
    • Fix: Use php -r "echo (new JakubOnderka\PhpConsoleColor\ConsoleColor())->getColoredString('Test', 'green');" to test environments. Fallback to plain text if unsupported:
      if (!ConsoleColor::isSupported()) {
          return $text; // Fallback
      }
      
  2. Performance:

    • Issue: Overusing ConsoleColor in loops (e.g., logging thousands of rows) can slow output.
    • Fix: Batch colorization or use only for critical messages.
  3. Deprecation:

Debugging Tips

  • Verify Support:
    if (!ConsoleColor::isSupported()) {
        throw new \RuntimeException('Console colors not supported in this environment.');
    }
    
  • Reset Colors: Always end colored output with ConsoleColor::RESET to avoid bleeding into subsequent text:
    echo $color->getColoredString('Error', 'red') . ConsoleColor::RESET;
    

Extension Points

  1. Custom Color Palette: Extend the class to add domain-specific colors (e.g., #FF5733 for "urgent"):

    class ExtendedConsoleColor extends ConsoleColor {
        public function getOrangeString($text) {
            return $this->getColoredString($text, '#FF5733');
        }
    }
    
  2. Integration with Laravel’s Termwind: For modern Laravel apps, combine with termwind for richer CLI styling:

    use Termwind\Components\DIV;
    
    DIV::new()->bgGray(800)->textGreen('Success')->render();
    
  3. Testing: Mock ConsoleColor in unit tests to avoid environment-dependent failures:

    $mockColor = $this->createMock(ConsoleColor::class);
    $mockColor->method('getColoredString')->willReturn('Mocked: ' . $text);
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests