Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get repository in command symfony6

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
    {
        $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 from Command, we could remove the configure method and do it in the constructor instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading