首页 > 代码库 > php faker 库填充数据

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.

php faker 库填充数据