我在我正在处理的应用程序中有一个Media实体,它与其他几个实体有关联:扬声器,标签,类别等.
在下面的代码中,我展示了我编写的用于创建一些测试数据的夹具.为了设置和分配数据之间的众多关系,显然很长.
public function load(ObjectManager $manager)
{
$videoType = new Mediatype();
$videoType->setName('video');
$videoType->setType('video');
$manager->persist($videoType);
$speaker1 = new Speaker();
$speaker1->setName('Joe Bloggs');
$speaker1->setBiography('Joe Bloggs bio.');
$manager->persist($speaker1);
$category1 = new Category();
$category1->setName('PHP');
$category1->setSlug('PHP');
$manager->persist($category1);
$tag1 = new Tag();
$tag1->setName('PHPNW');
$tag1->setSlug('PHPnw');
$manager->persist($tag1);
$video1 = new Media();
$video1->setMediatype($videoType);
$video1->setSpeakers(
new ArrayCollection(
array(
$speaker1
)
)
);
$video1->setCategories(
new ArrayCollection(
array(
$category1
)
)
);
$video1->setTags(
new ArrayCollection(
array(
$tag1
)
)
);
$video1->setDate(new Datetime());
$video1->setCreationDate(new DateTime());
$video1->setTitle('My video about PHP');
$video1->setDescription('A video about PHP!');
$video1->setContent('http://some.video-url.com');
$video1->setLength('20:00:00');
$video1->setRating(2.5);
$video1->setVisits(100);
$video1->setLanguage('EN');
$video1->setHostName('PHP');
$video1->setHostUrl('PHP');
$video1->setStatus('pub');
$manager->persist($video1);
$manager->flush();
}
现在我想用真实数据替换这个夹具,并在一个夹具中加载十几个Media实体.我可以复制并粘贴它十几次并更改数据,但这很麻烦,难以维护.有没有一种很好的方法来加载这样的相同类型的众多实体? 解决方法: 我意识到doctrine/data-fixtures捆绑已经完全符合我的要求.
为此,我将每个实体加载到自己的夹具中并执行$this-> addReference(‘admin-user’,$user);使用$this-> getReference(‘admin-user’)从另一个夹具访问它;
加载依赖项的灯具也很容易:
public function getDependencies()
{
// fixture classes that this fixture is dependent on
return array('MyDataFixturesMyOtherFixture');
}
所以现在我的夹具看起来像这样:
public function load(ObjectManager $manager)
{
$video1 = new Media();
$video1->setMediatype($this->getReference('video'));
$video1->setSpeakers(
new ArrayCollection(
array(
$this->getReference('joe-bloggs')
)
)
);
$video1->setCategories(
new ArrayCollection(
array(
$this->getReference('PHP')
)
)
);
$video1->setTags(
new ArrayCollection(
array(
$this->getReference('PHPnw')
)
)
);
$video1->setDate(new Datetime());
$video1->setCreationDate(new DateTime());
$video1->setTitle('My video about PHP');
$video1->setDescription('A video about PHP!');
$video1->setContent('http://some.video-url.com');
$video1->setLength('20:00:00');
$video1->setRating(2.5);
$video1->setVisits(100);
$video1->setLanguage('EN');
$video1->setHostName('PHP');
$video1->setHostUrl('PHP');
$video1->setStatus('pub');
$manager->persist($video1);
$manager->flush();
}
/**
* Load this fixtures dependencies
* @see https://github.com/doctrine/data-fixtures
*
* @return array
*/
public function getDependencies()
{
return array(
'...LoadMediatypeData',
'...LoadSpeakerData',
'...LoadCategoryData',
'...LoadTagData'
);
}
(编辑:北几岛)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|