Yii2 使用 faker 生成假数据

本文介绍如何在Yii2.0框架中利用yii2-faker类库生成大量假数据,包括配置步骤、模版文件创建及执行命令生成假数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

测试过程中有时候需要生成大量的假数据,faker 是一个生成假数据的类库.Yii2.0已经集成该类库yii2-faker,不用再下载了。

以Yii2.0 advanced版为例:

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

'controllerMap' => [
    'fixture' => [
        'class' => 'yii\faker\FixtureController',
    ],
],
复制代码

注意顶部,定义tests测试目录的位置的代码。在console\config\bootstrap.php中添加

Yii::setAlias('@tests', dirname(__DIR__) . '/tests');
复制代码

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

在tests目录下面依次新建unit/templates/fixtures目录,然后在fixtures目录下新建blogs.php文件。内容如下:

<?php
// users.php file under template path (by default @tests/unit/templates/fixtures)
/**
 * @var $faker \Faker\Generator
 * @var $index integer
 */
return [
    'title' => $faker->title,
    'content' => $faker->realText,
    'views' => $faker->firstName,
    'is_delete' => $faker->boolean,
    'created_at' => $faker->date($format = 'Y-m-d', $max = 'now'),
    'updated_at' => $faker->date($format = 'Y-m-d', $max = 'now'),
    'file' => $faker->imageUrl($width = 640, $height = 480),
    'file2' => $faker->imageUrl($width = 640, $height = 480),
];
复制代码

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

php yii fixture/generate users --count=10
复制代码

生成的假数据位于tests\unit\fixtures\data\blogs.php,打开如下,有了假数据内容,剩下的就好办了

<?php

return [
    [
        'title' => 'Miss',
        'content' => 'King, with an anxious look at it!\' This speech caused a remarkable sensation among the people that walk with their fur clinging close to her, still it had VERY long claws and a crash of broken.',
        'views' => '丽丽',
        'is_delete' => true,
        'created_at' => '1977-04-04',
        'updated_at' => '2013-06-04',
        'file' => 'https://lorempixel.com/640/480/?42094',
        'file2' => 'https://lorempixel.com/640/480/?90710',
    ],
    [
        'title' => 'Mrs.',
        'content' => 'As soon as look at me like that!\' But she waited patiently. \'Once,\' said the Queen. \'Their heads are gone, if it please your Majesty,\' said the one who had spoken first. \'That\'s none of YOUR.',
        'views' => '帅',
        'is_delete' => true,
        'created_at' => '1996-08-25',
        'updated_at' => '2012-04-09',
        'file' => 'https://lorempixel.com/640/480/?44425',
        'file2' => 'https://lorempixel.com/640/480/?16747',
    ],
    ...
]
复制代码

转载于:https://juejin.im/post/5aa77043f265da2385328752

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值