Home > Article > Backend Development > Detailed introduction of Faker virtual data filling (with examples)
The content of this article is about the method (code example) of opening a new page link in the development of a small program. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Faker is a dummy data generator that can be used to populate databases for stress testing or create elegant XML documents.
Installation
If the project supports composer, use the following command to install it. If it is not supported, please download the source code from Faker's Github repository and put it into the project's expansion pack folder.
composer require fzaninotto/faker
To demonstrate the functionality, I created a new project using the following command:
// 创建新项目文件夹 mkdir data-seeder cd data-seeder // 安装 faker 扩展 composer require fzaninotto/faker
Basic usage
Create a test file in the root directory test.php, enter the following code:
<?php require_once __DIR__ . '/vendor/fzaninotto/faker/src/autoload.php'; $faker = Faker\Factory::create(); echo $faker->name, "\n"; echo $faker->address, "\n"; echo $faker->text;
Run the script in CLI mode, php test.php
View the output. The results of faker are randomly generated:
Prof. Kailyn Barton 9230 Herzog Groves Suite 005 Gusikowskihaven, CO 60533-4716 Nesciunt voluptas debitis iusto consectetur possimus mollitia in quam. Vel non rem temporibus illo numquam est. Sit fugit sed fugit id eligendi eaque sunt possimus.
Faker’s proper nouns
faker defines some proper nouns to help us understand its design ideas. Understand these Concepts are very helpful in understanding his source code.
In addition to the above three attributes, faker also provides a large number of simulation data to choose from. Each generator attribute (such as name
, address
and lorem
used above) is called a formatter (formatters).
There are many types of data we need to fill, such as
Basic random data: integers, floating point numbers, letters
Random character information: name, surname, first name, etc.
Random number: mobile phone number, phone number
Faker defines each category as a provider. View data-seeder/vendor/fzaninotto/faker/src/Faker/Provider to see the class files of various providers, as well as the files of language packs.
Source code analysis
faker Although the expansion package is small in size, it has all the essentials and is very valuable for learning.
faker object generation
View the factory method of faker generator:
const DEFAULT_LOCALE = 'en_US'; protected static $defaultProviders = array('Address', 'Barcode', 'Biased', 'Color', 'Company', 'DateTime', 'File', 'HtmlLorem', 'Image', 'Internet', 'Lorem', 'Miscellaneous', 'Payment', 'Person', 'PhoneNumber', 'Text', 'UserAgent', 'Uuid'); public static function create($locale = self::DEFAULT_LOCALE) { $generator = new Generator(); foreach (static::$defaultProviders as $provider) { $providerClassName = self::getProviderClassname($provider, $locale); $generator->addProvider(new $providerClassName($generator)); } return $generator; }
Parameterlocale
is the language package, the default is en_US
United States English. All supported language packs can be viewed in the data-seeder/vendor/fzaninotto/faker/src/Faker/Provider
directory.
The default providers (provider has been mentioned above) can be found in one-to-one correspondence in the above Provider directory. Loop through the array and add the corresponding provider to the generator $generator
.
protected static function getProviderClassname($provider, $locale = '') { if ($providerClass = self::findProviderClassname($provider, $locale)) { return $providerClass; } // fallback to default locale if ($providerClass = self::findProviderClassname($provider, static::DEFAULT_LOCALE)) { return $providerClass; } // fallback to no locale if ($providerClass = self::findProviderClassname($provider)) { return $providerClass; } throw new \InvalidArgumentException(sprintf('Unable to find provider "%s" with locale "%s"', $provider, $locale)); }
getProviderClassname will search for the provider class according to the following logic. If it does not exist in the current file, it will search for the next-level file. If it cannot find it, an exception will be thrown:
The language pack folder passed in by the user -> The default en_US language pack folder -> Provider root directory
public function addProvider($provider) { array_unshift($this->providers, $provider); }
addProvider is very simple, just Add the found provider to the head of the array, and the array is stored in the properties of the $generator
object that will be returned.
When using the object returned by faker, there are two ways: calling properties and calling methods. These calls will trigger the magic method:
public function format($formatter, $arguments = array()) { return call_user_func_array($this->getFormatter($formatter), $arguments); } public function __get($attribute) { return $this->format($attribute); } public function __call($method, $attributes) { return $this->format($method, $attributes); }
The logic of the two is similar. Here is the more troublesome __call
magic method. The magic method will pass the called method name and parameters into farmat
method.
public function getFormatter($formatter) { if (isset($this->formatters[$formatter])) { return $this->formatters[$formatter]; } foreach ($this->providers as $provider) { if (method_exists($provider, $formatter)) { $this->formatters[$formatter] = array($provider, $formatter); return $this->formatters[$formatter]; } } throw new \InvalidArgumentException(sprintf('Unknown formatter "%s"', $formatter)); }
$this->formatters
stores information related to the formatter mentioned in the faker proper noun. To facilitate understanding, here is an example of taking a random element in an array to illustrate these abstract concepts.
$faker->randomElement(['a', 'b', 'c']);
When this method is called, the magic method is triggered, and then each provider class is traversed to find whether this method exists. Until this method is found in Base.php
, the provider to be used at this time is Base.php
, and the formatter is the randomElement()
method .
Then you need to store the corresponding relationship of randomeElement() in Base to avoid traversing all providers again next time. This is the reason why $this->formatters
is implemented.
After this method returns the corresponding provider and formatters, it is called through call_user_func_array
and returns the result.
At this point, a complete faker
object generation and calling process is over.
The above is the detailed content of Detailed introduction of Faker virtual data filling (with examples). For more information, please follow other related articles on the PHP Chinese website!