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

Command Bundle Laravel Package

draw/command-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require draw/command-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Draw\Bundle\CommandBundle\DrawCommandBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration: Add to config/packages/draw_command.yaml:

    draw_command:
        sonata:
            commands:
                testCommand:
                    commandName: "app:test"
                    label: "Test Command"
                    icon: "fa-play"
    
  3. First Use Case:

    • Run a command via Sonata Admin: Navigate to the Sonata Admin dashboard, find the "Commands" section, and execute testCommand.
    • Check logs:
      php bin/console draw:command:list
      
      Verify the execution appears in the draw_command_execution table.

Implementation Patterns

Workflows

  1. Sonata Admin Integration:

    • Configure commands in config/packages/draw_command.yaml with commandName, label, and icon.
    • Access via Sonata Admin’s "Commands" tab (if the bundle provides a UI; otherwise, use the CLI).
  2. Logging Command Output:

    • Replace ConsoleOutput with BufferedConsoleOutput in bin/console:
      $application->run($input, new \Draw\Bundle\CommandBundle\Console\Output\BufferedConsoleOutput());
      
    • Logs are stored in draw_command_execution with output and error_output fields.
  3. Debugging Failed Commands:

    • Query the database for failed executions:
      SELECT * FROM draw_command_execution WHERE status = 'failed';
      
    • Use the output or error_output fields to diagnose issues.
  4. CLI vs. Admin Execution:

    • Commands run via CLI without BufferedConsoleOutput will log minimally (status only).
    • Commands run via Sonata Admin or CLI with BufferedConsoleOutput log full output.

Integration Tips

  • Custom Commands: Extend the bundle’s CommandExecution entity to add custom fields (e.g., user_id for tracking who ran the command).

    // src/Entity/CommandExecution.php
    namespace App\Entity;
    use Draw\Bundle\CommandBundle\Entity\CommandExecution as BaseExecution;
    
    class CommandExecution extends BaseExecution {
        private ?int $userId = null;
    }
    
  • Event Listeners: Subscribe to command.execute or command.post_execute events to trigger side effects (e.g., notifications).

    // src/EventListener/CommandListener.php
    namespace App\EventListener;
    use Draw\Bundle\CommandBundle\Event\CommandEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class CommandListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                'command.execute' => 'onCommandExecute',
            ];
        }
    
        public function onCommandExecute(CommandEvent $event) {
            // Logic here
        }
    }
    
  • Scheduled Commands: Use Symfony’s CronBundle or laravel-schedule (if using Laravel) to trigger commands via the bundle’s logger.


Gotchas and Tips

Pitfalls

  1. Ignored Commands:

    • Commands like help, doctrine:database:drop, and cache:clear are explicitly ignored by default.
    • Workaround: Override the ignored list by extending the bundle’s CommandLogger service.
      # config/services.yaml
      Draw\Bundle\CommandBundle\Command\CommandLogger:
          arguments:
              $ignoredCommands: ['help', 'custom:ignored']
      
  2. Output Buffering:

    • Forgetting to use BufferedConsoleOutput in bin/console means no output logging.
    • Fix: Wrap all CLI commands in the buffered output or use a global wrapper.
  3. Database Schema:

    • The bundle assumes the draw_command_execution table exists. Run migrations if missing:
      php bin/console doctrine:migrations:diff
      php bin/console doctrine:migrations:migrate
      
  4. Sonata Admin Visibility:

    • The bundle does not automatically add a Sonata Admin block. Manually register it in your admin class:
      // src/Admin/CommandAdmin.php
      use Draw\Bundle\CommandBundle\Admin\CommandAdmin;
      
      class CommandAdmin extends CommandAdmin {
          protected function configureSideMenu() {
              $this->menuChildren[] = ['route' => 'sonata_admin_command_list'];
          }
      }
      

Debugging Tips

  • Query Logs: Use draw:command:list to see all executions:

    php bin/console draw:command:list --format=json
    

    Filter by status:

    php bin/console draw:command:list --status=failed
    
  • Output Truncation: Long command outputs may be truncated in the database. Adjust the output column length in the migration if needed.

  • Performance: Logging every command execution can bloat the database. For high-frequency commands (e.g., cron jobs), consider:

    • Logging only failed executions.
    • Using a separate table for non-critical commands.

Extension Points

  1. Custom Fields: Extend the CommandExecution entity to store additional metadata (e.g., environment, priority).

    // src/Entity/CommandExecution.php
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity]
    class CommandExecution extends BaseExecution {
        #[ORM\Column(type: 'string', nullable: true)]
        private ?string $environment = null;
    }
    
  2. Predefined Arguments: The bundle lacks native support for command arguments. Implement a workaround:

    • Store arguments as JSON in a metadata column.
    • Use a custom form type in Sonata Admin to input arguments dynamically.
  3. Webhook Triggers: Extend the bundle to trigger commands via HTTP requests (e.g., for remote execution):

    // src/Controller/CommandController.php
    use Draw\Bundle\CommandBundle\Command\CommandExecutor;
    use Symfony\Component\HttpFoundation\Request;
    
    class CommandController {
        public function __construct(private CommandExecutor $executor) {}
    
        public function execute(Request $request, string $commandName) {
            $this->executor->execute($commandName, $request->query->all());
            return new Response('Command triggered');
        }
    }
    
  4. Slack/Email Notifications: Subscribe to the command.post_execute event to send notifications:

    // src/EventListener/NotificationListener.php
    use Draw\Bundle\CommandBundle\Event\CommandEvent;
    
    class NotificationListener {
        public function onCommandPostExecute(CommandEvent $event) {
            if ($event->getExecution()->getStatus() === 'failed') {
                // Send Slack/email alert
            }
        }
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware