首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取命令symfony6中的存储库

获取命令symfony6中的存储库
EN

Stack Overflow用户
提问于 2022-08-29 10:18:24
回答 1查看 42关注 0票数 1

我想使用存储库从DB中获取数据。

然而,在命令中,我如何获得存储库呢?

例如,我将SiteDataRepository放置在execute中,

代码语言:javascript
复制
protected function execute(SiteDataRepository $siteDataRepository,InputInterface $input, OutputInterface $output): int
{

然而,会有错误

代码语言:javascript
复制
Fatal error: Declaration of App\Command\OpArticleCommand::execute(App\Repository\SiteDataRepository $siteDataRepository,

或者在execute()中是否有任何方法来执行SQL sentence

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-29 10:27:12

您可以自动生成存储库,但不能直接在执行方法中使用。

添加一个构造函数(如果已经没有构造函数)来注入存储库服务。

如果您的命令扩展了Command,那么应该如下所示:

代码语言:javascript
复制
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)
        ;
    }
}

请注意,我们使用的是配置方法,因为我们不使用名称调用父构造函数,因此可以删除配置方法并在构造函数中执行它。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73527317

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档