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

Console Laravel Package

symfony/console

Symfony Console makes it easy to build beautiful, testable command-line applications in PHP. It provides structured commands, arguments and options, interactive prompts, styled output, helpers, and robust input/output handling for modern CLIs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require symfony/console
    

    Laravel already includes this package as a dependency via Symfony components.

  2. First Command: Create a basic command in app/Console/Commands/ (e.g., TestCommand.php):

    <?php
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    
    class TestCommand extends Command
    {
        protected $signature = 'test:greet {name?}';
        protected $description = 'Display a greeting';
    
        public function handle()
        {
            $name = $this->argument('name') ?: 'World';
            $this->info("Hello, {$name}!");
        }
    }
    

    Register it in app/Console/Kernel.php:

    protected $commands = [
        Commands\TestCommand::class,
    ];
    
  3. Run It:

    php artisan test:greet Laravel
    

Key Starting Points

  • Documentation: Symfony Console Component
  • Laravel Artisan: Built on top of Symfony Console (artisan is the CLI application).
  • Core Classes:
    • Symfony\Component\Console\Command\Command (base class for commands)
    • Symfony\Component\Console\Application (manages commands)
    • Symfony\Component\Console\Output\OutputInterface (output handling)

Implementation Patterns

1. Command Structure

Workflow:

  • Signature: Define input arguments/options using $signature (e.g., {name?} for optional args, --force for flags).
  • Description: Use $description for help text.
  • Handling: Implement handle() for command logic. Use $this->argument()/$this->option() to access inputs.

Example:

protected $signature = 'user:create {--admin} {name} {email}';
protected $description = 'Create a new user';

public function handle()
{
    $name = $this->argument('name');
    $email = $this->argument('email');
    $isAdmin = $this->option('admin');

    // Logic here...
}

2. Output Handling

Patterns:

  • Basic Output:
    $this->info('Success!');
    $this->error('Failed!');
    $this->line('Plain text');
    $this->comment('Hint');
    
  • Styling:
    $this->text('<options=bold>Bold</>');
    $this->text('<fg=green>Green</>');
    
  • Progress Bars:
    $progressBar = $this->output->createProgressBar(100);
    for ($i = 0; $i <= 100; $i++) {
        $progressBar->advance();
    }
    $progressBar->finish();
    

3. Input Validation

Patterns:

  • Argument/Option Validation: Use validateArguments() or validateOptions():
    protected function validateArguments()
    {
        if ($this->argument('name') === 'admin') {
            throw new \InvalidArgumentException('Name cannot be "admin".');
        }
    }
    
  • Choice Input:
    $choice = $this->choice('Select environment', ['dev', 'staging', 'prod'], 'dev');
    

4. Interactive Prompts

Patterns:

  • Confirm:
    if ($this->confirm('Proceed?', false)) {
        // ...
    }
    
  • Ask:
    $name = $this->ask('Your name');
    $secret = $this->secret('Password');
    
  • Hidden Input (e.g., passwords):
    $password = $this->askHidden('Password');
    

5. Command Testing

Patterns:

  • Unit Testing: Use Symfony\Component\Console\Tester\CommandTester:
    use Symfony\Component\Console\Tester\CommandTester;
    
    public function testCommand()
    {
        $command = new TestCommand();
        $commandTester = new CommandTester($command);
        $commandTester->execute(['name' => 'Laravel']);
    
        $this->assertEquals('Hello, Laravel!', trim($commandTester->getDisplay()));
    }
    
  • Integration Testing: Use Laravel’s Artisan::call():
    $exitCode = Artisan::call('test:greet', ['name' => 'Laravel']);
    $this->assertEquals(0, $exitCode);
    

6. Command Groups and Helpers

Patterns:

  • Group Commands: Use protected $group in Kernel.php to organize commands under namespaces:
    protected $commands = [
        'user' => [
            Commands\UserCreateCommand::class,
            Commands\UserListCommand::class,
        ],
    ];
    
    Run with:
    php artisan user:create
    
  • SymfonyStyle Helper: For richer output (tables, sections, progress):
    use Symfony\Component\Console\Style\SymfonyStyle;
    
    public function handle()
    {
        $io = new SymfonyStyle($this->output, $this->input);
        $io->title('My Command');
        $io->section('Details');
        $io->table(['Name', 'Email'], [['Laravel', 'laravel@example.com']]);
    }
    

7. Event Listeners and Subscribers

Patterns:

  • Events: Bind to console events (e.g., ConsoleEvents::COMMAND):
    use Symfony\Component\Console\ConsoleEvents;
    use Symfony\Component\Console\Event\ConsoleCommandEvent;
    
    public function boot()
    {
        $this->commands['test:greet']->listen(function (ConsoleCommandEvent $event) {
            if ($event->getInput()->hasParameterOption('--verbose')) {
                $event->getCommand()->getApplication()->getHelperSet()->set(new VerboseHelper());
            }
        });
    }
    

Gotchas and Tips

Pitfalls

  1. Output Buffering:

    • Avoid mixing echo with Symfony’s output methods (e.g., $this->line()). Use $this->output->write() for raw output.
    • Fix: Use $this->output->isDecorated() to check for ANSI support before styling.
  2. Signal Handling:

    • Commands may terminate abruptly on SIGINT (Ctrl+C). Use $this->input->isInteractive() to check for interactive mode.
    • Tip: Override handleSignal() in custom commands for graceful shutdowns:
      protected function handleSignal($signal, $previous)
      {
          $this->info('Shutting down...');
          return parent::handleSignal($signal, $previous);
      }
      
  3. Progress Bars in Sections:

    • Progress bars may not render correctly in ConsoleSectionOutput. Use $this->output->section() sparingly with progress bars.
    • Workaround: Disable sections or use $this->output->overwrite() carefully.
  4. Windows Line Endings:

    • \r\n line endings can break output formatting. Use $this->output->setDecorated(false) or normalize line endings:
      $this->output->write(str_replace("\r\n", "\n", $text));
      
  5. Argument Parsing:

    • Arguments/options with # (e.g., --env=#) may cause issues. Use $this->input->getArgumentOptionValue() to access them:
      $env = $this->input->getArgumentOptionValue('--env');
      
  6. Testing Quirks:

    • ApplicationTester may ignore interactive/verbosity flags if SHELL_VERBOSITY is set. Mock the environment:
      putenv('SHELL_VERBOSITY=1');
      

Debugging Tips

  1. Enable Verbose Output:

    php artisan command --verbose
    

    Or in code:

    $this->output->setVerbosity(self::VERBOSITY_VERBOSE);
    
  2. Inspect Input/Output: Dump raw input/output:

    $this->output->writeln('<comment>Input:</comment> ' . print_r($this->input->getArguments(), true));
    
  3. Check for Hidden Commands: Hidden commands (e.g., cache:clear) won’t appear in help. Use --all:

    php artisan --all
    
  4. Profile Commands: Enable profiling to debug performance:

    php artisan command --profile
    

    View results in var/profile/.


Extension Points

  1. Custom Helpers: Extend Symfony\Component\Console\Helper\HelperSet:
    $helperSet = $this->getHelper
    
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/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
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