tebazil/db-seeder

语言: PHP

git: https://github.com/tebazil/db-seeder

PHP数据库播种机。使用虚假数据轻松填充数据库。框架不可知。使用方便。
PHP database seeder. Easily fill your database with fake data. Framework agnostic. Easy to use.
README.md (中文)

PHP Db播种机

立即用虚假数据填充您的数据库!

  • 非常好用!
  • 使用经过时间考验的fzaninotto / faker发电机
  • 轻松将生成器映射到数据库列
  • 支持相关数据
  • 播种表的两种方法:生成器或普通数组
  • 能够使用自己的发电机
  • 现代IDE中的友好自动完成功能(在phpstorm中测试)

安装

安装此扩展的首选方法是通过composer。

要么跑

$ composer require tebazil/db-seeder

或添加

"tebazil/db-seeder": "*"

到composer.json文件的require部分。

快速开始

您可以使用生成的数据快速为数据库设定种子,如下所示:

$pdo = new PDO('mysql:localhost', 'root', 'test');
$seeder = new \tebazil\dbseeder\Seeder($pdo);
$generator = $seeder->getGeneratorConfigurator();
$faker = $generator->getFakerConfigurator();

$seeder->table('article')->columns([
    'id', //automatic pk
    'book_id', //automatic fk
    'name'=>$faker->firstName,
    'content'=>$faker->text
        ])->rowQuantity(30);


$seeder->table('book')->columns([
    'id',
    'name'=>$faker->text(20),
])->rowQuantity(30);

$seeder->table('category')->columns([
    'id',
    'book_id',
    'name'=>$faker->text(20),
    'type'=>$faker->randomElement(['shop','cv','test']),
])->rowQuantity(30);

$seeder->refill();

!警告! $ seeder->笔芯();截断指定的所有表,并使用提供的配置使用随机数据填充它们。如果您使用producton / sensible数据库,可能会删除敏感数据。知道你在做什么。

让我们看看这里发生了什么。首先,您正在创建一个pdo连接,并使用它初始化新的$ seeder对象。然后,您将创建一个生成器和faker包装器实例,以便从自动完成中受益。然后将每个表配置为播种器。然后,您要求重新填充所有已配置的表。而已。

从发电机填充表

每列配置适当的生成器。发电机可以有5种类型: 1)PK。自增量PK(尚不支持复合键) 2)关系。与某些表列的值的关系 3)任何faker发电机 4)匿名功能 5)标量值

1)PK。表的pk是id,只留下id。它会被自动视为PK。如果它不是id,则必须使用完整语法来配置PK

...
'book_id'=> $generator->pk
...

2)关系。当前关系是当您从另一个或当前表中的某些列中随机填充某些列时。 如果您的关系正好是some_table_name_id并且还正在配置该表名,则可以保持原样。正确的关系将被自动检测并自动设置。如果没有,您将不得不使用完整的语法。以下是从book_category.id列填充的表book中设置列parent_id的示例:

...
'parent_id'=>$generator->relation('book_category', 'id'),
...

3)Faker发电机。事实上它很容易使用它们。只需确保在配置列时使用$ faker = \ tebazil \ dbseeder \ FakerWrapper()而不是真正的faker实例。调用faker方法(使用我们的无参数)和属性,就像你通常从faker中调用它们一样,使用唯一和可选的前缀,并从默认语言环境的自动完成中受益--FakerWrapper可以做到这一切。请参阅[如何工作]部分以了解更多有关我们未在此处使用Faker实例的原因。 例子:

...
'first_name'=>$faker->firstName,
'preview'=>$faker->text(20),
'content'=>$faker->text,
'type'=>$faker->randomElement(['shop','cv','test']),
...

4)匿名函数或其他php callables。 匿名函数只需要返回一些可以写入相应数据库列的标量值。例如,您可以使用它们来执行一些精确的随机选择生成器。 明显的例子是:

'user_id'=>function() {
  return rand(1, 234343);
}

5)纯粹的价值。 每行的此字段使用相同的值。

'is_active'=>1

注意:您不能将这些值用作普通值类型:  任何php可调用字符串(它们将被调用)  'PK'  '关系'  '骗子'

从数组填充表

您也可以直接从数组中填充表格。

对于具有数字键的数组,您必须显式定义相应的列名。如果您不想使用某些列,只需使用false / null进行列配置。如果不配置某些数组列,则不会使用它们。

$array =
 [
    [1,'twinsen','the heir'],
    [2,'zoe', 'self-occupied'],
    [3, 'baldino', 'twinsunian elephant']
 ];
 $columnConfig = [false,'name','occupation'];

$seeder->table('users')->data($array, $columnConfig)->rowQuantity(30);

对于具有与表列对应的键的数组,可以省略列配置。

关于rowQuantity的注意事项

您可以为每个表设置所需的行数量。如果未设置,将使用默认值(30)。对于从数组填充,逻辑是这样的:如果不定义行数,则将填充所有数组。如果在提供的数组中使用的值大于“lines”的数量,则会迭代给定的数组以填充所需的行数。如果提供的值小于数组的行数,则将使用该行数。

怎么运行的

当你发出这样的命令

$seeder->table('category')->columns([
    'id',
    'book_id',
    'name'=>$faker->text(20),
    'type'=>$faker->randomElement(['shop','cv','test']),
])->rowQuantity(30);

没有对您的数据库做任何事情。调用refill()方法时,它首先填充不依赖于其他表的表。然后迭代以填充其他(从属)表。

Q&A

问:为什么你使用faker包装而不是faker实例? 答:简答:提供更简洁,更整洁的语法。答案很长:Faker生成器会在您调用时立即提供虚假数据。我们需要为我们填写的每个字段提供数据,而不仅仅是一次。因此,每次我们需要不同的值时,我们可以使用匿名函数从faker获取一些数据结果:

'first_name'=>function() use($faker) { return $faker->firstName; }

($ faker是一个真正的骗子实例)

或者,如果我们在这里使用FakerWrapper,我们可以使用更清晰的语法:

'first_name'=>$faker->firstName

($ faker是一个包装)

本文使用googletrans自动翻译,仅供参考, 原文来自github.com

en_README.md

PHP Db Seeder

Have your database populated with fake data in no time!

  • Very easy to use!
  • Use time-tested fzaninotto/faker generators
  • Easily map generators to database columns
  • Supports related data
  • Two ways of seeding a table: generators or plain array
  • Ability to use your own generators
  • Friendly autocomplete in modern IDE's (tested in phpstorm)

Installation

The preferred way to install this extension is through composer.

Either run

$ composer require tebazil/db-seeder

or add

"tebazil/db-seeder": "*"

to the require section of your composer.json file.

Quick start

You can quickly seed your database with generated data with something like this:

$pdo = new PDO('mysql:localhost', 'root', 'test');
$seeder = new \tebazil\dbseeder\Seeder($pdo);
$generator = $seeder->getGeneratorConfigurator();
$faker = $generator->getFakerConfigurator();

$seeder->table('article')->columns([
    'id', //automatic pk
    'book_id', //automatic fk
    'name'=>$faker->firstName,
    'content'=>$faker->text
        ])->rowQuantity(30);


$seeder->table('book')->columns([
    'id',
    'name'=>$faker->text(20),
])->rowQuantity(30);

$seeder->table('category')->columns([
    'id',
    'book_id',
    'name'=>$faker->text(20),
    'type'=>$faker->randomElement(['shop','cv','test']),
])->rowQuantity(30);

$seeder->refill();

!!! Caution! $seeder->refill(); truncates all the tables specified and fills them with random data using the configuration provided. Sensible data might be deleted if you operate on producton/sensible database. Know what you are doing.

Let's see what happens here. First, you are creating a pdo connection, and initializing new $seeder object with it. Then you create a generator and faker wrappers instances to benefit from autocompletion. Then you configure each table for seeder. Then you ask to refill all configured tables. That's it.

Filling table from generators

Each column is configured with appropriate generator. Generators can be of 5 types:
1) PK. Self incrementing PK (No support for composite keys yet)
2) Relation. Relation to some table column's value
3) Any faker generator
4) Anonymous function
5) Scalar value

1) PK. Table's pk is id, just leave id. It will be treated as PK automatically. If it isn't id, you'll have to use full syntax to configure PK

...
'book_id'=> $generator->pk
...

2) Relation. Currently relation is when you fill some column randomly from some column that is in the other or current table.
If your relation is exactly some_table_name_id and that table name is also being configured, you can leave just as it is. Correct relation will be autodetected and set automatically. If not, you will have to use full syntax. Here is the example for setting column parent_id from table book being populated from book_category.id column:

...
'parent_id'=>$generator->relation('book_category', 'id'),
...

3) Faker generators. If fact it is very easy to use them. Just make sure you use $faker = \tebazil\dbseeder\FakerWrapper() instead of real faker instance when configuring columns. Call faker methods (with our without params) and attributes, as you would normally call them from faker, use unique and optional prefixes and benefit from autocompletion for the default locale - FakerWrapper can do all that. See [How it works] section to know more on why we are not using Faker instance here.
Examples:

...
'first_name'=>$faker->firstName,
'preview'=>$faker->text(20),
'content'=>$faker->text,
'type'=>$faker->randomElement(['shop','cv','test']),
...

4) Anonymous functions or other php callables.
Anonymous function just has to return some scalar value that can be written to the appropriate database column. You can use them to do some precise random choice generators, for example.
Obvious example would be:

'user_id'=>function() {
  return rand(1, 234343);
}

5) Plain value.
Same value is used for this field for each row.

'is_active'=>1

Note: you cannot use these values as plain value types:
Any php callable string (they will be called instead)
'pk'
'relation'
'faker'

Filling table from array

You can also fill the table directly from array.

For arrays with numeric keys you have to explicitly define the corresponding column names. If you do not want to use some column, just use false/null for column configuration. If you do not configure some array columns, they will not be used.

$array =
 [
    [1,'twinsen','the heir'],
    [2,'zoe', 'self-occupied'],
    [3, 'baldino', 'twinsunian elephant']
 ];
 $columnConfig = [false,'name','occupation'];

$seeder->table('users')->data($array, $columnConfig)->rowQuantity(30);

For arrays with keys corresponding to table columns you can omit the column configuration.

Note on rowQuantity

You can set the desired row quantity for each table. If not set the default value(30) will be used. For filling from array the logic is this: if you don't define row quantity, all array will be filled. If you use the value greater than quantity of "lines" in the array provided, given array will be iterated over to fill as much lines as it is needed. If you provide the value lesser than array's number of lines, that number of lines will be used.

How it works

When you issue commands like this

$seeder->table('category')->columns([
    'id',
    'book_id',
    'name'=>$faker->text(20),
    'type'=>$faker->randomElement(['shop','cv','test']),
])->rowQuantity(30);

nothing is done to your database. When refill() method is called, it first fills the tables that are not dependent on others. Then it iterates over to fill other (dependent) tables.

Q&A

Q: Why do you use faker wrapper instead of faker instance?
A: Short answer: to provide a shorter and neater syntax. Long answer: Faker generators provides the fake data immediately when you call it. We need that data to be available for each field we fill, not just one time. So, we can use anonymous function to fetch some data result from faker each time we need a different value like this:

'first_name'=>function() use($faker) { return $faker->firstName; }

($faker is a real faker instance)

Or we can use much cleaner syntax if we use FakerWrapper here:

'first_name'=>$faker->firstName

($faker is a wrapper)