Generating Fake Data in PHP with Faker

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.

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

  1. Aspose.Cells 首次使用,用到模版填充数据,合并单元格,换行

    Aspose.Cells 首次使用,用到模版填充数据,合并单元格,换行 模版格式,图格式是最简单的格式,但实际效果不是这种,实际效果图如图2 图2 ,注意看红色部分,一对一是正常的,但是有一对多的订单 ...

  2. Laravel使用Seeder自动填充数据

    要查看代码,可以点击 或者转到链接:https://github.com/laravel/framework Laravel自动填充数据使用的是Seeder类 <?php use Illumin ...

  3. laravel框架一种方便的快速填充数据的方法

    首先大家都知道在laravel框架里是采用seeder来填充数据的,具体命令如下,请将如下的类名称替换成你具体的seeder类名. 首先创建seeder类 php artisan make:seede ...

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

    使用Faker生成虚拟数据 创建虚拟数据是编写Web程序时的常见需求.在简单的场景下,我们可以手动创建一些虚拟数据,但更方便的选择是使用第三方库实现.流行的python虚拟数据生成工具有Mimesis ...

  5. 基于echarts 24种数据可视化展示,填充数据就可用,动手能力强的还可以DIY(演示地址+下载地址)

    前言 我们先跟随百度百科了解一下什么是"数据可视化 [1]". 数据可视化,是关于数据视觉表现形式的科学技术研究. 其中,这种数据的视觉表现形式被定义为,一种以某种概要形式抽提出来 ...

  6. laravel7 数据迁移及填充数据

    1:置迁移数据表,创建生成模型和迁移文件: php artisan make:model Article -m 2:接着,在框架中的database/migrations文件夹中找到刚创建的用户表Ar ...

  7. 使用SQLServer同义词和SQL邮件,解决发布订阅中订阅库丢失数据的问题

    最近给客户做了基于SQLServer的发布订阅的“读写分离”功能,但是某些表数据很大,经常发生某几条数据丢失的问题,导致订阅无法继续进行.但是每次发现问题重新做一次发布订阅又非常消耗时间,所以还得根据 ...

  8. SQL Server 跨库同步数据

    最近有个需求是要跨库进行数据同步,两个数据库分布在两台物理计算机上,自动定期同步可以通过SQL Server代理作业来实现,但是前提是需要编写一个存储过程来实现同步逻辑处理.这里的存储过程用的不是op ...

  9. dataguard从库移动数据文件

    ------------方法1从库移动数据文件路径方法1--------------将表空间offline的方法不行 1.退出日志应用alter database recover managed st ...

随机推荐

  1. 存储过程使用 in 添加多个参数的情况处理方式【转】

    原文连接:http://www.jb51.net/article/41472.htm -->情景 ① 通过刚才的SQL递归方式,我们已经可以将一个组织机构和其全部下级单位查询出来:假设每个组织机 ...

  2. 转战JS(1) 初探与变量类型、运算符、常用函数与转换

    转战JS(1)初探与变量类型.运算符.常用函数与转换 做为一名.NET后台开发人员,正考滤向Web前端开发转型,之前也写过一代前端代码,可是当再回头看JS,并有转向它的意愿的时候,突然发现:原来JS不 ...

  3. SQL 性能不佳的几个原因

    •不准确的统计数据•差劲的索引•差劲的查询设计 •差劲的执行计划,通常是由不正确的参数引起的•过度阻塞和死锁 •非基于集合的操作•不良数据库设计 •过度碎片 •不能重复使用执行计划 •查询频繁重编译 ...

  4. 'javac' 不是内部或外部命令,也不是可运行的程序

    今天在命令行中运行javac命令时发现 但是运行java命令却可以 查找jdk的安装路径发现,安装目录里面同时有jdk的文件夹和jre的文件夹 查看了jdk的目录发现jdk目录中也有一个jre文件夹 ...

  5. 【Alpha 冲刺】 9/12

    今日任务总结 人员 今日原定任务 完成情况 遇到问题 贡献值 胡武成 完善API文档,并初步使用SpringMVC产生编写部分API 已完成 孙浩楷 完成课程通知页面(及发布通知的弹窗) 已完成 胡冰 ...

  6. 用AOP拦截自定义注解并获取注解属性与上下文参数(基于Springboot框架)

    目录 自定义注解 定义切面 获取上下文信息JoinPoint ProceedingJoinPoint 定义测试方法 测试结果 小结 AOP可以用于日志的设计,这样话就少不了要获取上下文的信息,博主在设 ...

  7. Linux平台安装Oracle11gR2数据库

    1. 数据库安装先决条件 1.1 认证的操作系统检查确认 o RHEL4,OEL4 - update 7 or greater o RHEL5,OEL5 - 5.2 or greater o RHEL ...

  8. poi 创建excel数据

    public static void main(String[] args) throws Exception { // TODO 设置excel的标题 List<String> exce ...

  9. 网络嗅探与欺骗(FTP部分)——P201421410029

    第三部分 FTP协议分析 1. 两个同学一组,A和B. 2.A同学架设FTP服务器,并设置用户名和密码,例如wbx /wbx 3.B同学在机器中安装Wireshark,并将其打开:之后用用户名和密码登 ...

  10. shiro实战系列(十一)之Caching

    Shiro 开发团队明白在许多应用程序中性能是至关重要的.Caching 是从第一天开始第一个建立在 Shiro 中的一流功 能,以确保安全操作保持尽可能的快.   然而,Caching 作为一个概念 ...