首页 > 代码库 > Yii2 使用 faker 生成假数据

Yii2 使用 faker 生成假数据

Yii2使用 faker 生成假数据。

1. config\console.php 中添加一条配置信息

‘controllerMap‘ => [    ‘fixture‘ => [        ‘class‘ => ‘yii\faker\FixtureController‘,    ],],

注意顶部,定义test测试目录的位置的代码。

Yii::setAlias(‘@tests‘, dirname(__DIR__) . ‘/tests‘);

2. 创建生成假信息的模版文件

在test目录下面依次新建unit/templates/fixtures目录

然后在fixtures目录下新建users.php文件。内容如下:

// users.php file under template path (by default @tests/unit/templates/fixtures)/** * @var $faker \Faker\Generator * @var $index integer */return [    ‘name‘ => $faker->firstName,    ‘phone‘ => $faker->phoneNumber,    ‘city‘ => $faker->city,    ‘password‘ => Yii::$app->getSecurity()->generatePasswordHash(‘password_‘ . $index),    ‘auth_key‘ => Yii::$app->getSecurity()->generateRandomString(),    ‘intro‘ => $faker->sentence(7, true),  // generate a sentence with 7 words];

3. 打开命令行,执行生成假记录命令 

php yii fixture/generate users

生成的假数据位于tests\unit\fixtures\data\users.php

内容

<?phpreturn [    [        ‘name‘ => ‘Dawn‘,        ‘phone‘ => ‘1-931-080-3527x751‘,        ‘city‘ => ‘Schinnerberg‘,        ‘password‘ => ‘$2y$13$ax7ubTMdQoUBkAdQfgW38uPD3Lp9C/X7XfdfSMFl8L1N90PpdXQoK‘,        ‘auth_key‘ => ‘zmk_N4ZX_kOgu72iiWvPFZDUHEhQGYsg‘,        ‘intro‘ => ‘Adipisci nostrum et autem molestias odio.‘,    ],    [        ‘name‘ => ‘Hubert‘,        ‘phone‘ => ‘1-618-327-3265x917‘,        ‘city‘ => ‘Auerstad‘,        ‘password‘ => ‘$2y$13$gSjD/GJZiuPQdjB5FXyf0.fZCD9Jm6KquYRFyoaU6fgT3HHHiRa/q‘,        ‘auth_key‘ => ‘zAVYEriQJJF16DtwwzesVM84gA1UhxFK‘,        ‘intro‘ => ‘Maiores voluptas possimus nihil nesciunt qui commodi maiores qui.‘,    ],];

 

Yii2 使用 faker 生成假数据