脚本宝典收集整理的这篇文章主要介绍了php – 以简洁的方式加载数十个数据夹具,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
在下面的代码中,我展示了我编写的用于创建一些测试数据的夹具.为了设置和分配数据之间的众多关系,显然很长.
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实体.我可以复制并粘贴它十几次并更改数据,但这很麻烦,难以维护.有没有一种很好的方法来加载这样的相同类型的众多实体?
为此,我将每个实体加载到自己的夹具中并执行$this-> addReference(‘admin-user’,$user);使用$this-> getReference(‘admin-user’)从另一个夹具访问它;
加载依赖项的灯具也很容易:
public function getDependencies() { // fixture classes that this fixture is dependent on return array('MyDataFixtures\MyOtherFixture'); }
所以现在我的夹具看起来像这样:
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' ); }
以上是脚本宝典为你收集整理的php – 以简洁的方式加载数十个数据夹具全部内容,希望文章能够帮你解决php – 以简洁的方式加载数十个数据夹具所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。