Symfony 3.4使用3.0版本DoctrineFixturesBundle执行命令报错
我之前帮朋友排查过一模一样的问题——在Symfony 3.0环境用DoctrineFixturesBundle 3.0执行$ php bin/console doctrine:fixtures:load时,弹出Could not find any fixture services to load的错误。本质上就是你的Fixture类没被系统识别成可用的服务,或者配置环节有遗漏,下面是几个必查的点:
1. 先确认Fixture类的“身份”和位置
你的Fixture类得放在正确的目录里,一般是src/AppBundle/DataFixtures/ORM/(如果你的主Bundle是AppBundle的话),而且命名空间必须对应,还要正确继承新的Fixture基类:
// src/AppBundle/DataFixtures/ORM/LoadUserData.php namespace AppBundle\DataFixtures\ORM; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Common\Persistence\ObjectManager; use AppBundle\Entity\User; class LoadUserData extends Fixture { public function load(ObjectManager $manager) { // 举个例子,创建测试用户 $testUser = new User(); $testUser->setUsername('demo_user'); // ... 其他字段设置 $manager->persist($testUser); $manager->flush(); } }
划重点:必须继承Doctrine\Bundle\FixturesBundle\Fixture,别用旧版的Doctrine\Common\DataFixtures\Fixture,3.0版本的Bundle已经换基类了。
2. 检查配置:让系统找到你的Fixture
Symfony 3.0里,得确保Bundle能扫描到你的Fixture类,并且把它们注册成服务。
- 先看
app/config/config.yml里的DoctrineFixtures配置:
# app/config/config.yml doctrine_fixtures: dirs: ['%kernel.root_dir%/../src/AppBundle/DataFixtures/ORM'] namespace: AppBundle\DataFixtures\ORM
如果你的Fixture不在默认目录,这里要改成你实际的路径。
- 要是用服务自动配置(Symfony 3.0可能需要手动加),得在
app/config/services.yml里添上规则,给Fixture类打上识别标签:
# app/config/services.yml services: _defaults: autowire: false autoconfigure: true public: false AppBundle\DataFixtures\ORM\: resource: '../../src/AppBundle/DataFixtures/ORM/*' tags: ['doctrine.fixture.orm']
这条配置会把该目录下的所有Fixture类都标记成Doctrine能识别的服务。
3. 清缓存!清缓存!清缓存!
Symfony的缓存经常会搞事情,尤其是服务注册的变化,先清掉缓存再试:
$ php bin/console cache:clear --env=dev
别嫌麻烦,很多时候清完缓存问题就没了。
4. 检查文件名和类名的一致性
PSR-4自动加载规则要求文件名和类名必须完全一致,包括大小写!比如LoadUserData.php对应LoadUserData类,要是写成loaduserdata.php或者类名是LoaduserData,自动加载就找不到类,服务自然注册失败。
5. 确认Bundle已经注册到Kernel里
最后再核对下app/AppKernel.php,确保DoctrineFixturesBundle已经加进去了:
// app/AppKernel.php public function registerBundles() { $bundles = [ // ... 其他Bundle new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(), // ... ]; // ... }
要是以上都检查完还不行,用这条命令看看系统里已经注册的Fixture服务:
$ php bin/console debug:container --tag=doctrine.fixture.orm
如果列表里没有你的Fixture类,那肯定是服务注册的环节出问题了,再回头看配置和命名空间。
内容的提问来源于stack exchange,提问作者Ashfaq Muhammad

