php faker 库填充数据

Generating Fake Data in PHP with Faker

时间 2016-01-28 07:13:00 Wern Ancheta

原文  http://wern-ancheta.com/blog/2016/01/28/generating-fake-data-in-php-with-faker/

主题 PHP

In the good old days, I often test PHP applications by accessing it directly from the browser and input the data in the forms. Today, with the explosion of awesome PHP libraries you can now generate most kinds of data by using code alone. The data can then be directly inserted into the database. This reduces the need to input data directly into the app. In this tutorial, I’ll be walking you through Faker , a PHP library that generates fake data for you.

Installation

You can install Faker by executing the following command. Note that this requires you to have Composer installed.

composer require fzaninotto/faker

Concepts

Here are a few concepts that you need to remember before moving on.

  • generators – responsible for generating data.
  • providers – the data source for generators. Generators can’t really stand by themselves. Providers really shine on the localization feature of Faker. Real places, phone numbers in countries can be generated by Faker through the use of providers.
  • formatters – these are the properties that you can access from a specific generator. Examples include name, city, address, and phoneNumber.

Usage

To use Faker from your file, you need to include the vendor autoload file and create a new Faker instance.

<?php
require_once ‘vendor/autoload.php‘;

$faker = Faker\Factory::create();
?>

Localization

Since Faker is an open-source project that anyone can contribute to, lots of localized providers has already been added. You can take advantage of this by passing in the locale when you create a new Faker instance. For example, if you live in the Philippines:

<?php
$faker = Faker\Factory::create(‘en_PH‘);
?>

You can then generate an address in the Philippines by using the address formatter. Note that it’s only down to the city level. This means that the street and barangay are using the default providers.

<?php
echo $faker->address;
?>

Note that each provider doesn’t have generators for every possible formatter. For example, the Philippine provider has only generators for the Address and PhoneNumber. This means that you can only have localized values for those. All the other formatters will utilize the default ones provided by Faker. For a list of providers, check out this page in their Github repo.

Formatters

Here are the formatters that I commonly use in my projects.

<?php
//person
$faker->name;
$faker->firstName(‘male‘);
$faker->lastName;

//address
$faker->address;
$faker->streetName;
$faker->streetAddress;
$faker->postCode;
$faker->address;
$faker->country;

//company
$faker->company;

//date and time
$faker->year;
$faker->month; //number representation of a month
$faker->monthName;
$faker->timezone; //valid php timezone (http://php.net/manual/en/timezones.php)
$faker->time; //string time
$faker->dateTime; //datetime object
$faker->unixTime; //unix timestamp

//internet
$faker->email;
$faker->userName;
$faker->password;

//payment
$faker->creditCardType;
$faker->creditCardNumber;

//images
$faker->imageUrl(50, 60); //where width=50 and height=60
?>

Creating New Providers

If you want to create a provider for your own project, you can easily extend Faker. For example, if you want to generate random pokemon names. The first thing that you need to do is to declare the namespace in which the class belongs. Next, declare a new class and have it extend the faker provider base class. Inside the class, create an array of Pokemon names. Create a new function and call it pokemon , this is the function that will be called later on to generate a random pokemon name. To pick a random item from the array you created, use the randomElement function and then pass in the array which you want to use as the data source.

<?php
namespace Faker\Provider;

class Pokemon extends \Faker\Provider\Base {

  protected static $pokemon = array(
    ‘Pikachu‘,
    ‘Bulbasaur‘,
    ‘Cubone‘,
    ‘Charizard‘,
    ‘Marowak‘,
    ‘Gastly‘,
    ‘Alakazam‘,
    ‘Arcanine‘,
    ‘Vaporeon‘,
    ‘Flareon‘,
    ‘Venusaur‘,
    ‘Wartortle‘
  );

  public function pokemon(){
    return static::randomElement(static::$pokemon);
  }
}
?>

Save the file and name it Pokemon.php . You can save it any where in your project as long as you can easily reference it from your main file.

On your main file, include the vendor autoload together with the file that you’ve just created.

<?php
require_once ‘vendor/autoload.php‘;
require_once ‘Pokemon.php‘;
?>

Create a new faker generator. This is a bare bones generator with no providers assigned to it. So if you use $faker->name , all you get is an error.

<?php
$faker = new Faker\Generator();
?>

If you want to use the default providers, you can include them by calling the addProvider method and passing in a new instance of the provider that you want to include.

<?php
$faker->addProvider(new Faker\Provider\en_US\Person($faker));
$faker->addProvider(new Faker\Provider\en_US\Address($faker));
$faker->addProvider(new Faker\Provider\en_US\PhoneNumber($faker));
$faker->addProvider(new Faker\Provider\en_US\Company($faker));
$faker->addProvider(new Faker\Provider\Lorem($faker));
$faker->addProvider(new Faker\Provider\Internet($faker));
?>

To add the new Pokemon provider.

<?php
$faker->addProvider(new Faker\Provider\Pokemon($faker));
?>

Once that’s done, you can now call the new pokemon formatter.

<?php
$faker->pokemon; //marowak
?>

Integration with Your PHP Application

Most PHP frameworks today already comes with a database seeding feature. If you’re using Laravel, it has a database migration and seeding functionality . You can simply install Faker into your project, generate a new seeder and then use Faker inside the seeder. This allows you to seed your database with Fake data in a single command by using Artisan CLI . If your framework doesn’t include a seeding feature, you can use Phinx, a database-migration tool for PHP. This tool also allows you to create seeders for your database .

Conclusion

That’s it! In this tutorial, you’ve learned how to work with the Faker library to generate fake and random data for testing your PHP applications. Check out the official github page for more information regarding its usage.

时间: 2024-10-12 14:28:18

php faker 库填充数据的相关文章

Flask实战-留言板-使用Faker生成虚拟数据

使用Faker生成虚拟数据 创建虚拟数据是编写Web程序时的常见需求.在简单的场景下,我们可以手动创建一些虚拟数据,但更方便的选择是使用第三方库实现.流行的python虚拟数据生成工具有Mimesis和Faker,后者同时支持python2和python3,而且文档中包含丰富的示例,所以这里选用Faker.首先用pipenv安装(使用—dev选项声明为开发依赖):pipenv install faker --dev Faker内置了20多类虚拟数据,包括姓名.地址.网络账号.信用卡.时间.职位.

困扰已久——DataGridView控件填充数据时自动添加列

    机房重构慢慢的走到了尽头,最近正在进行最后的润色中,今天解决了一个困扰许久但是非常简单的问题.我们在查询上机和充值记录时,用到了DataGridView控件.我们在VB版的机房收费系统中也用过类似的,不过显然没有.NET中如此灵活呀!     在填充数据时,我们分明已经写好了控件的列名,可是在填充数据时,会向DataGridView后面自动增加列,然后填充增加的列的数据,效果如下:    解决方法:        其中,DataPropertyName是绑定的数据源或者数据库中对应的字段

【数据处理】大库订货数据匹配

select  distinct a.商品编码,a.品名,a.规格,a.最终进价 大库价格,c.curcsprc 进价,a.最终进价-c.curcsprc 差价,d.qty 西部,e.qty 东部,f.qty 中区from lhdh201408 aleft join lhspm b on a.商品编码=b.pluidleft join 商品码 c on b.barcode=c.bcdleft join (select pluno,sum(qty) qty from xbxs where rq b

SQL Server 跨库同步数据

最近有个需求是要跨库进行数据同步,两个数据库分布在两台物理计算机上,自动定期同步可以通过SQL Server代理作业来实现,但是前提是需要编写一个存储过程来实现同步逻辑处理.这里的存储过程用的不是opendatasource,而是用的链接服务器来实现的.存储过程创建在IP1:192.168.0.3服务器上,需要将视图v_custom的客户信息同步到IP2:192.168.0.10服务器上的t_custom表中.逻辑是如果不存在则插入,存在则更新字段. 1 create PROCEDURE [db

sqoop从关系库导出数据到hive

[Author]: kwu sqoop从关系库导出数据到hive,sqoop支持条件查询关系库中的数到hive数据仓库中,并且字段无须与hive表中的字段一致. 具体实现的脚本: #!/bin/sh # upload logs to hdfs today=`date --date='0 days ago' +%Y-%m-%d` sqoop import --connect jdbc:mysql://10.130.2.6:3306/bdc_test --username lvwenjuan --p

批量删除mysql一个库所有数据表方法

批量删除mysql一个库所有数据表方法 删除表的命令 drop table 表名; 如果有100张表,手工执行100次,想想就崩溃. 下面提供一个使用information_schema库的方案来批量删除数据表:SELECT CONCAT('drop table ',table_name,';') FROM information_schema.`TABLES` WHERE table_schema='数据库名'; 如通过这条命令来得到drop table 表名;这样的语句,然后批量执行.mys

C#动态生成Word文档并填充数据

C#也能动态生成Word文档并填充数据 http://www.cnblogs.com/qyfan82/archive/2007/09/14/893293.html 引用http://blog.csdn.net/mengyao/archive/2007/09/13/1784079.aspx using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.

sharepoint给文档库每个数据条添加权限

前言 老大任务,做一个读取文档库把里面的每一条数据添加权限.挺起来很简单,但是做起来,还是很简单,哈哈.因为我没有接触过这些代码,所以得不断的请教了.大题明白了,简单实现了一下,应用控制台先做了一下简单的功能,里面有写死的,但是完全可以写活. 代码部分 //读取网站集 SPSite site = new SPSite ("http://localhost"); SPWebApplication webApp = site.WebApplication; SPWeb web = site

Yii2 使用 faker 生成假数据

Yii2使用 faker 生成假数据. 1. config\console.php 中添加一条配置信息 'controllerMap' => [ 'fixture' => [ 'class' => 'yii\faker\FixtureController', ], ], 注意顶部,定义test测试目录的位置的代码. Yii::setAlias('@tests', dirname(__DIR__) . '/tests'); 2. 创建生成假信息的模版文件 在test目录下面依次新建unit