根据官方文档对Fixture进行学习
首先使用
composer require --dev doctrine/doctrine-fixtures-bundle
来导入扩展
之后注意,如果symfony版本不是3以下的,需要添加数组元素到AppKernel当中,即下列语句,注意添加到in_array对应的那块
$bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle();
FixtureBundle本质上可以看作一个php类,创建一个Fixture类,用它来,使用
Doctrine\Common\Persistence\ObjectManage 的ObjectManage类来托管(persist)需要加入的对象实体,对对象实体进行初始化,之后使用 flush方法来更新入数据库当中
namespace App\DataFixtures;use App\Entity\Product;use Doctrine\Bundle\FixturesBundle\Fixture;use Doctrine\Common\Persistence\ObjectManager;class AppFixtures extends Fixture{ public function load(ObjectManager $manager) { // create 20 products! Bam! for ($i = 0; $i < 20; $i++) { $product = new Product(); $product->setName('product '.$i); $product->setPrice(mt_rand(10, 100)); $manager->persist($product); } $manager->flush(); }}
之后命令行执行
php bin/console doctrine:fixtures:load
将数据更新入数据库当中 除此之外,如果你想讲services和Fixture相结合的话,你的Fixture就可以当做是一个Services进行使用,可以注入任何东西,实例,这里的就是说可以在Fixture当中添加构造函数,变量等, 注意这里的encoder->encodePassword方法可以对密码进行加密,具体实现不说了,
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;// ...private $encoder;public function __construct(UserPasswordEncoderInterface $encoder){ $this->encoder = $encoder;}// ...public function load(ObjectManager $manager){ $user = new User(); $user->setUsername('admin'); $password = $this->encoder->encodePassword($user, 'pass_1234'); $user->setPassword($password); $manager->persist($user); $manager->flush();}
同时可以在一个Fixture当中调用另一个Fixture,一个Fixture当中使用
this->addReference(self::ADMIN_USER_REFERENCE, $userAdmin);
将$userAdmin变量交给addReference,之后在另一个Fixture当中,使用getReference方法来获得$userAdmin变量,参数为,类名:add时候的别名
$userGroup->addUser($this->getReference(UserFixtures::ADMIN_USER_REFERENCE));
具体实例如下
// src/DataFixtures/UserFixtures.php// ...class UserFixtures extends Fixture{ public const ADMIN_USER_REFERENCE = 'admin-user'; public function load(ObjectManager $manager) { $userAdmin = new User('admin', 'pass_1234'); $manager->persist($userAdmin); $manager->flush(); // other fixtures can get this object using the UserFixtures::ADMIN_USER_REFERENCE constant $this->addReference(self::ADMIN_USER_REFERENCE, $userAdmin); }}// src/DataFixtures/GroupFixtures.php// ...class GroupFixtures extends Fixture{ public function load(ObjectManager $manager) { $userGroup = new Group('administrators'); // this reference returns the User object created in UserFixtures $userGroup->addUser($this->getReference(UserFixtures::ADMIN_USER_REFERENCE)); $manager->persist($userGroup); $manager->flush(); }}
个人感觉这个东西和doctrine的getManager方法差不多,都是对对象进行托管,之后更新入数据库当中,