我想知道有关Symfony2的DataFixtures的最佳实践。例如,我有Role
和User
。
RoleFixtures:
class RoleFixtures extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function load(ObjectManager $manager)
{
$userRole = new Role();
$userRole->setName("user");
$userRole->setRole("ROLE_USER");
$manager->persist($userRole);
$manager->flush();
$adminRole = new Role();
$adminRole->setName("admin");
$adminRole->setRole("ROLE_ADMIN");
$manager->persist($adminRole);
$manager->flush();
}
public function getOrder()
{
return 1;
}
UserFixtures:
class UserFixtures extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function load(ObjectManager $manager)
{
$roleManager = $this->container->get('elite_fifa.role_manager');
$userRole = $roleManager->getRoleByName("user");
$adminRole = $roleManager->getRoleByName("admin");
$userManager = $this->container->get('elite_fifa.user_manager');
$user1 = $userManager->createUser();
$user1->setUsername("user1");
$user1->setEmail("my1@email.com");
$user1->addRole($userRole);
$encoder = $this->container->get('security.encoder_factory')->getEncoder($user1);
$encodedPass = $encoder->encodePassword('pass1', $user1->getSalt());
$user1->setPassword($encodedPass);
$manager->persist($user1);
$manager->flush();
$user2 = $userManager->createUser();
$user2->setUsername("user2");
$user2->setEmail("my2@email.com");
$user2->addRole($adminRole);
$encoder = $this->container->get('security.encoder_factory')->getEncoder($user2);
$encodedPass = $encoder->encodePassword('pass2', $user1->getSalt());
$user2->setPassword($encodedPass);
$manager->persist($user2);
$manager->flush();
}
public function getOrder()
{
return 2;
}
}
看看UserFixtures中的load方法,我可以使用$roleManager->getRoleByName("user")
而不是使用references
中内置的DataFixtures吗?
我在考虑这样做,我正在重用代码并添加另一条路径进行测试。但是将Fixtures与bundle逻辑结合起来是不好的做法?感谢
答案 0 :(得分:2)
对我来说,这取决于一个问题:你使用这些灯具做什么?