As a developer almost every project that I am working needs some dummy data. Because without data I cannot test my application in which I am working. In the old days of my programming I usually create a form and insert dummy data. To be very honest I hate that process because data insertion took lot of time.
But now lots of PHP libraries are available to tackle this problem. Faker is one of them. Faker is a fake data library inspired by PERL’s Data::Faker and by RUBY’s Faker. As per official definition.
Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.
Faker Installation:
There are 3 ways to download Faker. Composer, GIT and direct download .In this tutorial I am going to download Faker via GIT.
GIT Link:
https://github.com/fzaninotto/Faker.git
Direct Download Link:
https://github.com/fzaninotto/Faker/archive/master.zip
Composer Command:
composer require fzaninotto/faker
After downloading Faker via GIT its directory structure will look like this.
For now there are 2 important folders, one is src and second is test. SRC folder has all the source of Faker Library. And in the test folder you can see its documentation and test file. I am going to work on test directory. Now I am going to create a file as hello-world.php and include faker autoload file and create its instance.
Also visit Insert dummy data into MYSQL using PHP
Usage:
Hello-world.php:
1 2 3 4 5 6 7 8 9 10 11 |
<?php require '../src/autoload.php'; $faker = Faker\Factory::create(); echo $faker->name; echo “<br>”; echo $faker->address; echo “<br>”; echo $faker->text; ?> |
I created $faker
as an instance. Factory::create()
can take a locale as an argument and returned localized data but by default it takes en_US. You can check available Faker locale in the src\Faker\Provider directory. $faker->name
returns different name so as $faker->address
and $faker->text
.
Get Data Using Loop:
If I want to get multiple values of faker then.
1 2 3 4 5 6 7 8 9 10 11 |
<?php for ($i = 0; $i < 10; $i++) { echo "Name: " . $faker->name . "<br>"; echo "Address: " . $faker->address . "<br>"; echo "Text: " . $faker-> text. "<br>"; echo "<hr>"; } ?> |
Formatters:
Formatters are the faker properties (name, address, text). Faker provides loads of formatters under “providers”. I am going to show some of the most frequent used formatters. If you want to read all of them then you can visit https://github.com/fzaninotto/Faker#formatters
Base Providers:
1 2 3 4 5 6 7 8 9 10 |
<?php $faker->randomDigit // 7 $faker->randomDigitNotNull // 5 $faker->randomNumber($nbDigits = NULL, $strict = false) // 79907610 $faker->randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932 $faker->numberBetween($min = 1000, $max = 9000) // 8567 $faker->randomLetter // 'b' ?> |
Lorem Providers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $faker->word // 'aut' $faker->words($nb = 3, $asText = false) // array('porro', 'sed', 'magni') $faker->sentence($nbWords = 6, $variableNbWords = true) // 'Sit vitae voluptas sint non voluptates.' $faker->sentences($nb = 3, $asText = false) // array('Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.') $faker->paragraph($nbSentences = 3, $variableNbSentences = true) // 'Ut ab voluptas sed a nam. Sint autem inventore aut officia aut aut blanditiis. Ducimus eos odit amet et est ut eum.' $faker->paragraphs($nb = 3, $asText = false) // array('Quidem ut sunt et quidem est accusamus aut. Fuga est placeat rerum ut. Enim ex eveniet facere sunt.', 'Aut nam et eum architecto fugit repellendus illo. Qui ex esse veritatis.', 'Possimus omnis aut incidunt sunt. Asperiores incidunt iure sequi cum culpa rem. Rerum exercitationem est rem.') $faker->text($maxNbChars = 200) // 'Fuga totam reiciendis qui architecto fugiat nemo. Consequatur recusandae qui cupiditate eos quod.' ?> |
Person Providers: (Default en_US)
This provider is worked with localization. If you pass different locale parameter in Factory::create()
then result will come up according to that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $faker->cityPrefix // 'Lake' $faker->secondaryAddress // 'Suite 961' $faker->state // 'NewMexico' $faker->stateAbbr // 'OH' $faker->citySuffix // 'borough' $faker->streetSuffix // 'Keys' $faker->buildingNumber // '484' $faker->city // 'West Judge' $faker->streetName // 'Keegan Trail' $faker->streetAddress // '439 Karley Loaf Suite 897' $faker->postcode // '17916' $faker->address // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473' $faker->country // 'Falkland Islands (Malvinas)' $faker->latitude($min = -90, $max = 90) // 77.147489 $faker->longitude($min = -180, $max = 180) // 86.211205 ?> |
PhoneNumber Providers: (Default en_US)
This provider is also worked like person providers.
1 2 3 4 5 6 7 |
<?php $faker->phoneNumber // '201-886-0269 x3767' $faker->tollFreePhoneNumber // '(888) 937-7238' $faker->e164PhoneNumber // '+27113456789' ?> |
Company Providers: (Default en_US)
1 2 3 4 5 6 7 8 9 |
<?php $faker->catchPhrase // 'Monitored regional contingency' $faker->bs // 'e-enable robust architectures' $faker->company // 'Bogan-Treutel' $faker->companySuffix // 'and Sons' $faker->jobTitle // 'Cashier' ?> |
Text Providers: (Default en_US)
1 2 3 4 5 |
<?php $faker->realText($maxNbChars = 200, $indexSize = 2) // "And yet I wish you could manage it?) 'And what are they made of?' Alice asked in a shrill, passionate voice. 'Would YOU like cats if you were never even spoke to Time!' 'Perhaps not,' Alice replied." ?> |
DateTime Providers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $faker->iso8601($max = 'now') // '1978-12-09T10:10:29+0000' $faker->date($format = 'Y-m-d', $max = 'now') // '1979-06-09' $faker->time($format = 'H:i:s', $max = 'now') // '20:49:42' $faker->amPm($max = 'now') // 'pm' $faker->dayOfMonth($max = 'now') // '04' $faker->dayOfWeek($max = 'now') // 'Friday' $faker->month($max = 'now') // '06' $faker->monthName($max = 'now') // 'January' $faker->year($max = 'now') // '1993' $faker->century // 'VI' $faker->timezone // 'Europe/Paris' ?> |
Internet Providers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php $faker->email // 'tkshlerin@collins.com' $faker->safeEmail // 'king.alford@example.org' $faker->freeEmail // 'bradley72@gmail.com' $faker->companyEmail // 'russel.durward@mcdermott.org' $faker->freeEmailDomain // 'yahoo.com' $faker->safeEmailDomain // 'example.org' $faker->userName // 'wade55' $faker->password // 'k&|X+a45*2[' $faker->domainName // 'wolffdeckow.net' $faker->domainWord // 'feeney' $faker->tld // 'biz' $faker->url // 'http://www.skilesdonnelly.biz/aut-accusantium-ut-architecto-sit-et.html' $faker->slug // 'aut-repellat-commodi-vel-itaque-nihil-id-saepe-nostrum' $faker->ipv4 // '109.133.32.252' $faker->localIpv4 // '10.242.58.8' $faker->ipv6 // '8e65:933d:22ee:a232:f1c1:2741:1f10:117c' $faker->macAddress // '43:85:B7:08:10:CA' ?> |
UserAgent Providers:
1 2 3 4 5 6 7 8 9 10 |
<?php $faker->userAgent // 'Mozilla/5.0 (Windows CE) AppleWebKit/5350 (KHTML, like Gecko) Chrome/13.0.888.0 Safari/5350' $faker->chrome // 'Mozilla/5.0 (Macintosh; PPC Mac OS X 10_6_5) AppleWebKit/5312 (KHTML, like Gecko) Chrome/14.0.894.0 Safari/5312' $faker->firefox // 'Mozilla/5.0 (X11; Linuxi686; rv:7.0) Gecko/20101231 Firefox/3.6' $faker->safari // 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_7_1 rv:3.0; en-US) AppleWebKit/534.11.3 (KHTML, like Gecko) Version/4.0 Safari/534.11.3' $faker->opera // 'Opera/8.25 (Windows NT 5.1; en-US) Presto/2.9.188 Version/10.00' $faker->internetExplorer // 'Mozilla/5.0 (compatible; MSIE 7.0; Windows 98; Win 9x 4.90; Trident/3.0)' ?> |
Payment Providers:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $faker->creditCardType // 'MasterCard' $faker->creditCardNumber // '4485480221084675' $faker->creditCardExpirationDate // 04/13 $faker->creditCardExpirationDateString // '04/13' $faker->creditCardDetails // array('MasterCard', '4485480221084675', 'Aleksander Nowak', '04/13') // Generates a random IBAN. Set $countryCode to null for a random country $faker->iban($countryCode) // 'IT31A8497112740YZ575DJ28BP4' $faker->swiftBicNumber // 'RZTIAT22263' ?> |
Color Providers:
1 2 3 4 5 6 7 8 |
$faker->hexcolor // '#fa3cc2' $faker->rgbcolor // '0,255,122' $faker->rgbColorAsArray // array(0,255,122) $faker->rgbCssColor // 'rgb(0,255,122)' $faker->safeColorName // 'fuchsia' $faker->colorName // 'Gainsbor' |
File Providers:
1 2 3 4 5 6 7 8 9 |
<?php $faker->fileExtension // 'avi' $faker->mimeType // 'video/x-msvideo' // Copy a random file from the source to the target directory and returns the fullpath or filename $faker->file($sourceDir = '/tmp', $targetDir = '/tmp') // '/path/to/targetDir/13b73edae8443990be1aa8f1a483bc27.jpg' $faker->file($sourceDir, $targetDir, false) // '13b73edae8443990be1aa8f1a483bc27.jpg' ?> |
Image Providers:
1 2 3 4 5 6 7 8 |
<?php // Image generation provided by LoremPixel (http://lorempixel.com/) $faker->imageUrl($width = 640, $height = 480) // 'http://lorempixel.com/640/480/' $faker->imageUrl($width, $height, 'cats') // 'http://lorempixel.com/800/600/cats/' $faker->imageUrl($width, $height, 'cats', true, 'Faker') // 'http://lorempixel.com/800/400/cats/Faker' ?> |
Miscellaneous Providers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $faker->boolean // false $faker->boolean($chanceOfGettingTrue = 50) // true $faker->md5 // 'de99a620c50f2990e87144735cd357e7' $faker->sha1 // 'f08e7f04ca1a413807ebc47551a40a20a0b4de5c' $faker->sha256 // '0061e4c60dac5c1d82db0135a42e00c89ae3a333e7c26485321f24348c7e98a5' $faker->locale // en_UK $faker->countryCode // UK $faker->languageCode // en $faker->currencyCode // EUR $faker->emoji // 😁 ?> |
Conclusion:
In testing we always need some data to insert in database. Instead of manually insert value against every column, faker allows you to generate various kinds of random data for testing.