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 Helpers Laravel Package

queents/console-helpers

View on GitHub
Deep Wiki
Context7

Getting Started

Start by installing the package via Composer:

composer require queents/console-helpers

First Use Case: Replace a manual shell_exec call in an Artisan command with the RunCommand trait.

  1. Add the trait to your command:
    use Queents\ConsoleHelpers\Traits\RunCommand;
    
    class MyCommand extends Command {
        use RunCommand;
    }
    
  2. Replace shell_exec('php artisan migrate') with:
    $this->artisanCommand('migrate');
    

Where to Look First:

  • README.md for trait examples.
  • config/console-helpers.php (if created) for configurable paths (e.g., Yarn).
  • Docs for advanced stub templating or module management.

Implementation Patterns

1. Command Execution Workflows

Pattern: Use traits to centralize CLI logic in Artisan commands.

// In a deployment command
$this->yarnCommand('install --dev');
$this->phpCommand('artisan optimize:clear');
$this->artisanCommand('migrate --force');

Workflow:

  1. Pre-command: Validate dependencies (e.g., Yarn installed) via config('console-helpers.yarn_path').
  2. Execution: Chain commands with $this->call() or $this->handle() for async workflows.
  3. Post-command: Log output or check exit codes:
    $exitCode = $this->phpCommand('php -v', true); // Returns exit code
    if ($exitCode !== 0) { $this->error('PHP command failed'); }
    

2. Stub Templating

Pattern: Generate dynamic files (e.g., API clients, config files) from stubs.

$this->generateStubs(
    __DIR__.'/stubs/UserModel.stub',
    app_path('Models/User.php'),
    ['namespace' => 'App\Models'],
    [app_path('Models/')] // Ensure directory exists
);

Workflow:

  • Store stubs in resources/stubs/ or a module-specific directory.
  • Use Str::lower() or Str::title() for dynamic replacements.
  • Validate paths before generation to avoid race conditions.

3. Module Management

Pattern: Toggle modules in bulk or per-module (requires laravel-modules).

// Activate all modules
$this->activeAllModules();

// Deactivate a specific module
$this->activeModule('Admin', false);

Workflow:

  • Run during deployments or feature flag updates.
  • Combine with HandleStubs to generate module-specific configs:
    $this->activeModule('Auth');
    $this->generateStubs('stubs/AuthConfig.stub', ...);
    

4. Integration with Laravel Ecosystem

Pattern: Use traits alongside Laravel’s built-in tools.

// Hybrid approach: Use Process facade for complex commands
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

try {
    $process = new Process(['php', 'artisan', 'queue:work']);
    $process->run();
    if (!$process->isSuccessful()) {
        throw new ProcessFailedException($process);
    }
} catch (ProcessFailedException $e) {
    $this->error($e->getMessage());
}

When to Use Which:

Tool Use Case Example
RunCommand trait Simple, trusted commands (e.g., yarn build) $this->yarnCommand('build')
Process facade Complex commands (timeouts, logging) Process::of('php artisan ...')->run()
Artisan::call() Internal Laravel commands Artisan::call('migrate')

Gotchas and Tips

Pitfalls

  1. Shell Injection Vulnerabilities:

    • Risk: $this->phpCommand('user_input') executes arbitrary shell code.
    • Fix: Sanitize inputs or use Laravel’s Process facade:
      $process = new Process(['php', 'artisan', 'migrate'], null, null, null, 60);
      $process->run();
      
  2. Stub Path Resolution:

    • Issue: generateStubs() fails if directories don’t exist.
    • Fix: Create directories dynamically:
      $path = app_path('Models/User.php');
      if (!file_exists(dirname($path))) {
          mkdir(dirname($path), 0755, true);
      }
      
  3. Module Management Assumptions:

    • Issue: HandleModules assumes laravel-modules is installed and configured.
    • Fix: Add a check:
      if (!class_exists(\NWidart\Modules\Module::class)) {
          $this->error('laravel-modules is required for module commands.');
          return 1;
      }
      
  4. Exit Code Ignorance:

    • Issue: $this->artisanCommand('migrate') silently fails if migration errors occur.
    • Fix: Capture exit codes:
      $exitCode = $this->artisanCommand('migrate', true);
      if ($exitCode !== 0) { $this->error('Migrations failed'); }
      
  5. Yarn Path Configuration:

    • Issue: yarnCommand fails if Yarn isn’t in PATH or config isn’t set.
    • Fix: Set the path in config/console-helpers.php:
      'yarn_path' => '/usr/local/bin/yarn',
      

Debugging Tips

  • Log Command Output:
    $this->phpCommand('php -v', true, function ($type, $buffer) {
        $this->line($buffer);
    });
    
  • Test Locally First:
    • Use php artisan command:test to validate stub generation or module toggling.
  • Check for Deprecated Methods:
    • Monitor the CHANGELOG for breaking changes.

Extension Points

  1. Customize Command Execution:

    • Extend the RunCommand trait to add timeouts or logging:
      protected function phpCommand(string $command, bool $returnOutput = false, ?Closure $callback = null): int|string {
          $process = new Process(['php', '-r', $command], null, null, null, 30); // 30s timeout
          $process->run($callback);
          return $process->isSuccessful() ? 0 : $process->getOutput();
      }
      
  2. Add Stub Placeholders:

    • Extend HandleStubs to support nested arrays or custom delimiters:
      $this->generateStubs(
          'stub.stub',
          'output.php',
          ['data' => ['key' => 'value']],
          [app_path()]
      );
      
  3. Module Lifecycle Hooks:

    • Trigger events before/after module activation:
      $this->activeModule('Auth', true, function () {
          $this->info('Auth module activated. Running post-activation tasks...');
      });
      

Configuration Quirks

  • No Default Config File:
    • The package doesn’t create config/console-helpers.php by default. Create it manually:
      return [
          'yarn_path' => env('YARN_PATH', 'yarn'),
          'php_path' => env('PHP_PATH', 'php'),
      ];
      
  • Stub File Encoding:
    • Ensure stub files use UTF-8 encoding to avoid encoding issues during replacement.

Performance Considerations

  • Avoid Blocking Commands:
    • Use Laravel queues for long-running commands (e.g., yarn build):
      dispatch(new BuildYarnAssets)->onQueue('yarn');
      
  • Cache Stub Outputs:
    • For frequently generated files, cache the output:
      $cacheKey = 'stub_output_' . md5($stubPath);
      if (Cache::has($cacheKey)) {
          return Cache::get($cacheKey);
      }
      $output = $this->generateStubs(...);
      Cache::put($cacheKey, $output, now()->addHours(1));
      
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle