我想使用存储库从DB中获取数据。
然而,在命令中,我如何获得存储库呢?
例如,我将SiteDataRepository放置在execute中,
protected function execute(SiteDataRepository $siteDataRepository,InputInterface $input, OutputInterface $output): int
{然而,会有错误
Fatal error: Declaration of App\Command\OpArticleCommand::execute(App\Repository\SiteDataRepository $siteDataRepository,或者在execute()中是否有任何方法来执行SQL sentence?
发布于 2022-08-29 10:27:12
您可以自动生成存储库,但不能直接在执行方法中使用。
添加一个构造函数(如果已经没有构造函数)来注入存储库服务。
如果您的命令扩展了Command,那么应该如下所示:
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)
;
}
}请注意,我们使用的是配置方法,因为我们不使用名称调用父构造函数,因此可以删除配置方法并在构造函数中执行它。
https://stackoverflow.com/questions/73527317
复制相似问题