theodordiaconu / doctrine-fixture-helper
此包已被废弃且不再维护。未建议替代包。
帮助您快速使用 Doctrine Fixtures
dev-master
2016-02-24 09:20 UTC
Requires
- php: >=5.4
- doctrine/doctrine-fixtures-bundle: 2.3.0
- fzaninotto/faker: 1.5.*@dev
This package is not auto-updated.
Last update: 2021-07-10 00:22:01 UTC
README
这个的主要思想是将您的 DataFixture 类解耦,以避免混乱,并使用一点函数式 PHP 编写优雅的代码。
这适用于 Doctrine 的 ODM 和 ORM。
安装
composer require theodordiaconu/doctrine-fixture-helper dev-master
将 fixtures 包添加到 AppKernel.php
new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
用法
为了了解它是如何工作的,让我们考虑以下场景
- 您想生成一批用户
- 您希望每个用户都有一定数量的博客文章
- 每篇博客文章可以由系统中的其他用户给出一定数量的评论。
在您的包的 DataFixtures/ORM 文件夹中,我们建议有一个配置类
class Configuration
{
const USERS = 100;
const BLOG_POSTS_PER_USER = 5;
const COMMENTS_PER_BLOG_POST = 15;
public static $jobTitles = [
'Manager', 'Customer Relation', 'Web-Consultant', 'Web Architect', 'Loan Provider', 'Boss'
];
}
让我们从用户开始。
use TD\FixtureHelper\BaseFixture;
class LoadUserData extends BaseFixture
{
public function doLoad()
{
$this->userService = $this->container->get('user_service');
$this->iterator(Configuration::USERS, function($index) {
$user = new User();
$user->setFirstname($this->faker->firstname());
$user->setLastname($this->faker->lastname());
$user->setJob($this->faker->randomElement(Configuration::$jobTitles));
$this->userService->doSomething($user);
return $user; // you must return the object.
}, 'user'); // note: user is our reference name, the script will create user-1, user-2, user-3 accordingly.
}
public function getOrder()
{
return 1;
}
}
现在让我们为每个用户创建一些博客文章
// in LoadBlogPostData.php
public function doLoad()
{
$this->iterator('user', function(User $user) { // this will iterate through all existing users
$this->iterator(Configuration::BLOG_POSTS_PER_USER, function($index) use ($user) {
$blog = new BlogPost($user);
$blog->setTitle($this->faker->sentence());
$blog->setText($this->faker->text());
return $blog;
}, 'post')
});
}
// update getOrder
现在让我们在博客文章上留下评论
// in LoadCommentData.php
public function doLoad()
{
$this->iterator('post', function(BlogPost $post) {
$this->iterator(Configuration::COMMENTS_PER_BLOG_POST, function($index) use ($post) {
$comment = new Comment($this->getRandomObject('user'));
$comment->setPost($post);
return $comment;
}, 'comment-for-'.$post->getId())
});
}
// update getOrder
结论
如您所注意到的,如果迭代器获取一个整数作为第一个参数,它会逐个迭代直到达到该限制,如果它获取一个字符串,它假设您想要迭代通过一个预先存在的对象引用的集合。
如您所见,我们用非常少的代码就写出了这个。无限可能。这将帮助您创建非常复杂且相互关联的实体。
API
$this->container // container
$this->manager // ObjectManager
$this->faker // faker
$this->getObjects('user') // will return all users
$this->getReference('user-1') // will return user-1
$this->getRandomObject('user') // will return a random element from user collection
看看 faker 辅助方法: https://github.com/fzaninotto/Faker