How can i inject dependencies to Symfony Console commands?

后端 未结 7 1017
醉话见心
醉话见心 2020-12-09 08:00

I\'m writing an open source application uses some Symfony components, and using Symfony Console component for interacting with shell.

But, i need to inject dependen

相关标签:
7条回答
  • 2020-12-09 08:24

    You can use ContainerCommandLoader in order to provide a PSR-11 container as follow:

    require 'vendor/autoload.php';
    
    $application = new Application('my-app', '1.0');
    
    $container = require 'config/container.php';
    
    // Lazy load command with container
    $commandLoader = new ContainerCommandLoader($container, [
        'app:change-mode' => ChangeMode::class,
        'app:generate-logs' => GenerateLogos::class,
    ]);
    
    $application->setCommandLoader($commandLoader);
    
    $application->run();
    

    ChangeMode class could be defined as follow:

    class ChangeMode extends Command
    {
    
        protected static $defaultName = 'app:change-mode';
    
        protected $container;
    
        public function __construct(ContainerInterface $container)
        {
            $this->container = $container;
            parent::__construct(static::$defaultName);
        }
    ...
    

    NB.: ChangeMode should be provided in the Container configuration.

    0 讨论(0)
提交回复
热议问题