Symfony6命令中如何获取Repository执行数据库操作?
在Symfony6命令类中获取Repository的正确方式
1. 构造函数注入Repository
你不能直接在execute()方法里添加Repository参数,因为Symfony命令的execute()方法签名是固定的,只能接收InputInterface和OutputInterface两个参数。正确的做法是通过构造函数依赖注入:
namespace App\Command; use App\Repository\SiteDataRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class OpArticleCommand extends Command { private $siteDataRepository; // 构造函数注入Repository public function __construct(SiteDataRepository $siteDataRepository) { $this->siteDataRepository = $siteDataRepository; parent::__construct(); // 必须调用父类构造函数 } protected function configure(): void { $this->setName('app:op-article'); // 设置自定义命令名称 // 可添加其他配置,比如命令描述、参数等 } protected function execute(InputInterface $input, OutputInterface $output): int { // 正常使用Repository操作数据 $siteData = $this->siteDataRepository->findAll(); // 编写你的业务逻辑... return Command::SUCCESS; } }
2. 其他执行SQL语句的方式
除了Repository,你还可以通过以下两种方式在命令中执行SQL:
方式一:用EntityManager执行DQL或原生SQL
通过构造函数注入EntityManagerInterface,实现ORM查询或原生SQL操作:
namespace App\Command; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class OpArticleCommand extends Command { private $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; parent::__construct(); } protected function execute(InputInterface $input, OutputInterface $output): int { // 执行DQL查询 $dql = 'SELECT s FROM App\Entity\SiteData s WHERE s.status = :status'; $siteDataList = $this->entityManager->createQuery($dql) ->setParameter('status', 1) ->getResult(); // 执行原生SQL查询 $rawData = $this->entityManager->getConnection() ->executeQuery('SELECT * FROM site_data WHERE status = ?', [1]) ->fetchAllAssociative(); return Command::SUCCESS; } }
方式二:直接用Doctrine DBAL Connection操作
如果不需要ORM实体映射,可注入Connection类直接执行原生SQL:
namespace App\Command; use Doctrine\DBAL\Connection; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class OpArticleCommand extends Command { private $connection; public function __construct(Connection $connection) { $this->connection = $connection; parent::__construct(); } protected function execute(InputInterface $input, OutputInterface $output): int { // 查询数据 $results = $this->connection->fetchAllAssociative( 'SELECT * FROM site_data WHERE id = ?', [123] ); // 执行更新操作 $this->connection->executeStatement( 'UPDATE site_data SET status = ? WHERE id = ?', [0, 123] ); return Command::SUCCESS; } }
内容的提问来源于stack exchange,提问作者whitebear
相关产品推荐
相关产品推荐

