[FIXED] get repository in command symfony6

Issue

I want to use repository to fetch the data from DB.

However in command how can I get the repository?

For example I put the SiteDataRepository in execute,

protected function execute(SiteDataRepository $siteDataRepository,InputInterface $input, OutputInterface $output): int
{

however there comes error

Fatal error: Declaration of App\Command\OpArticleCommand::execute(App\Repository\SiteDataRepository $siteDataRepository,

Or is there any method to do the SQL sentence in execute()?

Solution

You can autowire your repository but not directly in your execute method.

Add a constructor (if there is none already) to inject your repository service.

If your command extends Command it should be something like:

class YourCommand extends Command
{
    protected static $defaultName = 'command-name';
    protected static $defaultDescription = 'description';
    private SiteDataRepository $siteDataRepository;

    public function __construct(SiteDataRepository $siteDataRepository)
    {
        parent::__construct();
        $this->siteDataRepository = $siteDataRepository;
    }

    protected function configure()
    {
        $this
            ->setName(self::$defaultName)
            ->setDescription(self::$defaultDescription)
        ;
    }
}

Note that we are using the configure method because we do not call the parent constructor with a name, we could remove the configure method and do it in the constructor instead.

Answered By – Dylan KAS

Answer Checked By – Timothy Miller (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published