GithubHelp home page GithubHelp logo

faker's Introduction

Faker

Monthly Downloads Continuous Integration codecov SensioLabsInsight

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 is heavily inspired by Perl's Data::Faker, and by ruby's Faker.

Faker requires PHP >= 5.3.3.

Faker is archived. Read the reasons behind this decision here: https://marmelab.com/blog/2020/10/21/sunsetting-faker.html

Table of Contents

Installation

composer require fzaninotto/faker

Basic Usage

Autoloading

Faker supports both PSR-0 as PSR-4 autoloaders.

<?php
# When installed via composer
require_once 'vendor/autoload.php';

You can also load Fakers shipped PSR-0 autoloader

<?php
# Load Fakers own autoloader
require_once '/path/to/Faker/src/autoload.php';

alternatively, you can use any another PSR-4 compliant autoloader

Create fake data

Use Faker\Factory::create() to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want.

<?php
// use the factory to create a Faker\Generator instance
$faker = Faker\Factory::create();

// generate data by accessing properties
echo $faker->name;
  // 'Lucy Cechtelar';
echo $faker->address;
  // "426 Jordy Lodge
  // Cartwrightshire, SC 88120-6700"
echo $faker->text;
  // Dolores sit sint laboriosam dolorem culpa et autem. Beatae nam sunt fugit
  // et sit et mollitia sed.
  // Fuga deserunt tempora facere magni omnis. Omnis quia temporibus laudantium
  // sit minima sint.

Even if this example shows a property access, each call to $faker->name yields a different (random) result. This is because Faker uses __get() magic, and forwards Faker\Generator->$property calls to Faker\Generator->format($property).

<?php
for ($i = 0; $i < 10; $i++) {
  echo $faker->name, "\n";
}
  // Adaline Reichel
  // Dr. Santa Prosacco DVM
  // Noemy Vandervort V
  // Lexi O'Conner
  // Gracie Weber
  // Roscoe Johns
  // Emmett Lebsack
  // Keegan Thiel
  // Wellington Koelpin II
  // Ms. Karley Kiehn V

Tip: For a quick generation of fake data, you can also use Faker as a command line tool thanks to faker-cli.

Formatters

Each of the generator properties (like name, address, and lorem) are called "formatters". A faker generator has many of them, packaged in "providers". Here is a list of the bundled formatters in the default locale.

Faker\Provider\Base

randomDigit             // 7
randomDigitNot(5)       // 0, 1, 2, 3, 4, 6, 7, 8, or 9
randomDigitNotNull      // 5
randomNumber($nbDigits = NULL, $strict = false) // 79907610
randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932
numberBetween($min = 1000, $max = 9000) // 8567
randomLetter            // 'b'
// returns randomly ordered subsequence of a provided array
randomElements($array = array ('a','b','c'), $count = 1) // array('c')
randomElement($array = array ('a','b','c')) // 'b'
shuffle('hello, world') // 'rlo,h eoldlw'
shuffle(array(1, 2, 3)) // array(2, 1, 3)
numerify('Hello ###') // 'Hello 609'
lexify('Hello ???') // 'Hello wgt'
bothify('Hello ##??') // 'Hello 42jz'
asciify('Hello ***') // 'Hello R6+'
regexify('[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'); // [email protected]

Faker\Provider\Lorem

word                                             // 'aut'
words($nb = 3, $asText = false)                  // array('porro', 'sed', 'magni')
sentence($nbWords = 6, $variableNbWords = true)  // 'Sit vitae voluptas sint non voluptates.'
sentences($nb = 3, $asText = false)              // array('Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.')
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.'
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.')
text($maxNbChars = 200)                          // 'Fuga totam reiciendis qui architecto fugiat nemo. Consequatur recusandae qui cupiditate eos quod.'

Faker\Provider\en_US\Person

title($gender = null|'male'|'female')     // 'Ms.'
titleMale                                 // 'Mr.'
titleFemale                               // 'Ms.'
suffix                                    // 'Jr.'
name($gender = null|'male'|'female')      // 'Dr. Zane Stroman'
firstName($gender = null|'male'|'female') // 'Maynard'
firstNameMale                             // 'Maynard'
firstNameFemale                           // 'Rachel'
lastName                                  // 'Zulauf'

Faker\Provider\en_US\Address

cityPrefix                          // 'Lake'
secondaryAddress                    // 'Suite 961'
state                               // 'NewMexico'
stateAbbr                           // 'OH'
citySuffix                          // 'borough'
streetSuffix                        // 'Keys'
buildingNumber                      // '484'
city                                // 'West Judge'
streetName                          // 'Keegan Trail'
streetAddress                       // '439 Karley Loaf Suite 897'
postcode                            // '17916'
address                             // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473'
country                             // 'Falkland Islands (Malvinas)'
latitude($min = -90, $max = 90)     // 77.147489
longitude($min = -180, $max = 180)  // 86.211205

Faker\Provider\en_US\PhoneNumber

phoneNumber             // '201-886-0269 x3767'
tollFreePhoneNumber     // '(888) 937-7238'
e164PhoneNumber     // '+27113456789'

Faker\Provider\en_US\Company

catchPhrase             // 'Monitored regional contingency'
bs                      // 'e-enable robust architectures'
company                 // 'Bogan-Treutel'
companySuffix           // 'and Sons'
jobTitle                // 'Cashier'

Faker\Provider\en_US\Text

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."

Faker\Provider\DateTime

unixTime($max = 'now')                // 58781813
dateTime($max = 'now', $timezone = null) // DateTime('2008-04-25 08:37:17', 'UTC')
dateTimeAD($max = 'now', $timezone = null) // DateTime('1800-04-29 20:38:49', 'Europe/Paris')
iso8601($max = 'now')                 // '1978-12-09T10:10:29+0000'
date($format = 'Y-m-d', $max = 'now') // '1979-06-09'
time($format = 'H:i:s', $max = 'now') // '20:49:42'
dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Africa/Lagos')
dateTimeInInterval($startDate = '-30 years', $interval = '+ 5 days', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Antartica/Vostok')
dateTimeThisCentury($max = 'now', $timezone = null)     // DateTime('1915-05-30 19:28:21', 'UTC')
dateTimeThisDecade($max = 'now', $timezone = null)      // DateTime('2007-05-29 22:30:48', 'Europe/Paris')
dateTimeThisYear($max = 'now', $timezone = null)        // DateTime('2011-02-27 20:52:14', 'Africa/Lagos')
dateTimeThisMonth($max = 'now', $timezone = null)       // DateTime('2011-10-23 13:46:23', 'Antarctica/Vostok')
amPm($max = 'now')                    // 'pm'
dayOfMonth($max = 'now')              // '04'
dayOfWeek($max = 'now')               // 'Friday'
month($max = 'now')                   // '06'
monthName($max = 'now')               // 'January'
year($max = 'now')                    // '1993'
century                               // 'VI'
timezone                              // 'Europe/Paris'

Methods accepting a $timezone argument default to date_default_timezone_get(). You can pass a custom timezone string to each method, or define a custom timezone for all time methods at once using $faker::setDefaultTimezone($timezone).

Faker\Provider\Internet

email                   // '[email protected]'
safeEmail               // '[email protected]'
freeEmail               // '[email protected]'
companyEmail            // '[email protected]'
freeEmailDomain         // 'yahoo.com'
safeEmailDomain         // 'example.org'
userName                // 'wade55'
password                // 'k&|X+a45*2['
domainName              // 'wolffdeckow.net'
domainWord              // 'feeney'
tld                     // 'biz'
url                     // 'http://www.skilesdonnelly.biz/aut-accusantium-ut-architecto-sit-et.html'
slug                    // 'aut-repellat-commodi-vel-itaque-nihil-id-saepe-nostrum'
ipv4                    // '109.133.32.252'
localIpv4               // '10.242.58.8'
ipv6                    // '8e65:933d:22ee:a232:f1c1:2741:1f10:117c'
macAddress              // '43:85:B7:08:10:CA'

Faker\Provider\UserAgent

userAgent              // 'Mozilla/5.0 (Windows CE) AppleWebKit/5350 (KHTML, like Gecko) Chrome/13.0.888.0 Safari/5350'
chrome                 // 'Mozilla/5.0 (Macintosh; PPC Mac OS X 10_6_5) AppleWebKit/5312 (KHTML, like Gecko) Chrome/14.0.894.0 Safari/5312'
firefox                // 'Mozilla/5.0 (X11; Linuxi686; rv:7.0) Gecko/20101231 Firefox/3.6'
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'
opera                  // 'Opera/8.25 (Windows NT 5.1; en-US) Presto/2.9.188 Version/10.00'
internetExplorer       // 'Mozilla/5.0 (compatible; MSIE 7.0; Windows 98; Win 9x 4.90; Trident/3.0)'

Faker\Provider\Payment

creditCardType          // 'MasterCard'
creditCardNumber        // '4485480221084675'
creditCardExpirationDate // 04/13
creditCardExpirationDateString // '04/13'
creditCardDetails       // array('MasterCard', '4485480221084675', 'Aleksander Nowak', '04/13')
// Generates a random IBAN. Set $countryCode to null for a random country
iban($countryCode)      // 'IT31A8497112740YZ575DJ28BP4'
swiftBicNumber          // 'RZTIAT22263'

Faker\Provider\Color

hexcolor               // '#fa3cc2'
rgbcolor               // '0,255,122'
rgbColorAsArray        // array(0,255,122)
rgbCssColor            // 'rgb(0,255,122)'
safeColorName          // 'fuchsia'
colorName              // 'Gainsbor'
hslColor               // '340,50,20'
hslColorAsArray        // array(340,50,20)

Faker\Provider\File

fileExtension          // 'avi'
mimeType               // 'video/x-msvideo'
// Copy a random file from the source to the target directory and returns the fullpath or filename
file($sourceDir = '/tmp', $targetDir = '/tmp') // '/path/to/targetDir/13b73edae8443990be1aa8f1a483bc27.jpg'
file($sourceDir, $targetDir, false) // '13b73edae8443990be1aa8f1a483bc27.jpg'

Faker\Provider\Image

// Image generation provided by LoremPixel (http://lorempixel.com/)
imageUrl($width = 640, $height = 480) // 'http://lorempixel.com/640/480/'
imageUrl($width, $height, 'cats')     // 'http://lorempixel.com/800/600/cats/'
imageUrl($width, $height, 'cats', true, 'Faker') // 'http://lorempixel.com/800/400/cats/Faker'
imageUrl($width, $height, 'cats', true, 'Faker', true) // 'http://lorempixel.com/gray/800/400/cats/Faker/' Monochrome image
image($dir = '/tmp', $width = 640, $height = 480) // '/tmp/13b73edae8443990be1aa8f1a483bc27.jpg'
image($dir, $width, $height, 'cats')  // 'tmp/13b73edae8443990be1aa8f1a483bc27.jpg' it's a cat!
image($dir, $width, $height, 'cats', false) // '13b73edae8443990be1aa8f1a483bc27.jpg' it's a filename without path
image($dir, $width, $height, 'cats', true, false) // it's a no randomize images (default: `true`)
image($dir, $width, $height, 'cats', true, true, 'Faker') // 'tmp/13b73edae8443990be1aa8f1a483bc27.jpg' it's a cat with 'Faker' text. Default, `null`.

Faker\Provider\Uuid

uuid                   // '7e57d004-2b97-0e7a-b45f-5387367791cd'

Faker\Provider\Barcode

ean13          // '4006381333931'
ean8           // '73513537'
isbn13         // '9790404436093'
isbn10         // '4881416324'

Faker\Provider\Miscellaneous

boolean // false
boolean($chanceOfGettingTrue = 50) // true
md5           // 'de99a620c50f2990e87144735cd357e7'
sha1          // 'f08e7f04ca1a413807ebc47551a40a20a0b4de5c'
sha256        // '0061e4c60dac5c1d82db0135a42e00c89ae3a333e7c26485321f24348c7e98a5'
locale        // en_UK
countryCode   // UK
languageCode  // en
currencyCode  // EUR
emoji         // 😁

Faker\Provider\Biased

// get a random number between 10 and 20,
// with more chances to be close to 20
biasedNumberBetween($min = 10, $max = 20, $function = 'sqrt')

Faker\Provider\HtmlLorem

//Generate HTML document which is no more than 2 levels deep, and no more than 3 elements wide at any level.
randomHtml(2,3)   // <html><head><title>Aut illo dolorem et accusantium eum.</title></head><body><form action="example.com" method="POST"><label for="username">sequi</label><input type="text" id="username"><label for="password">et</label><input type="password" id="password"></form><b>Id aut saepe non mollitia voluptas voluptas.</b><table><thead><tr><tr>Non consequatur.</tr><tr>Incidunt est.</tr><tr>Aut voluptatem.</tr><tr>Officia voluptas rerum quo.</tr><tr>Asperiores similique.</tr></tr></thead><tbody><tr><td>Sapiente dolorum dolorem sint laboriosam commodi qui.</td><td>Commodi nihil nesciunt eveniet quo repudiandae.</td><td>Voluptates explicabo numquam distinctio necessitatibus repellat.</td><td>Provident ut doloremque nam eum modi aspernatur.</td><td>Iusto inventore.</td></tr><tr><td>Animi nihil ratione id mollitia libero ipsa quia tempore.</td><td>Velit est officia et aut tenetur dolorem sed mollitia expedita.</td><td>Modi modi repudiandae pariatur voluptas rerum ea incidunt non molestiae eligendi eos deleniti.</td><td>Exercitationem voluptatibus dolor est iste quod molestiae.</td><td>Quia reiciendis.</td></tr><tr><td>Inventore impedit exercitationem voluptatibus rerum cupiditate.</td><td>Qui.</td><td>Aliquam.</td><td>Autem nihil aut et.</td><td>Dolor ut quia error.</td></tr><tr><td>Enim facilis iusto earum et minus rerum assumenda quis quia.</td><td>Reprehenderit ut sapiente occaecati voluptatum dolor voluptatem vitae qui velit.</td><td>Quod fugiat non.</td><td>Sunt nobis totam mollitia sed nesciunt est deleniti cumque.</td><td>Repudiandae quo.</td></tr><tr><td>Modi dicta libero quisquam doloremque qui autem.</td><td>Voluptatem aliquid saepe laudantium facere eos sunt dolor.</td><td>Est eos quis laboriosam officia expedita repellendus quia natus.</td><td>Et neque delectus quod fugit enim repudiandae qui.</td><td>Fugit soluta sit facilis facere repellat culpa magni voluptatem maiores tempora.</td></tr><tr><td>Enim dolores doloremque.</td><td>Assumenda voluptatem eum perferendis exercitationem.</td><td>Quasi in fugit deserunt ea perferendis sunt nemo consequatur dolorum soluta.</td><td>Maxime repellat qui numquam voluptatem est modi.</td><td>Alias rerum rerum hic hic eveniet.</td></tr><tr><td>Tempore voluptatem.</td><td>Eaque.</td><td>Et sit quas fugit iusto.</td><td>Nemo nihil rerum dignissimos et esse.</td><td>Repudiandae ipsum numquam.</td></tr><tr><td>Nemo sunt quia.</td><td>Sint tempore est neque ducimus harum sed.</td><td>Dicta placeat atque libero nihil.</td><td>Et qui aperiam temporibus facilis eum.</td><td>Ut dolores qui enim et maiores nesciunt.</td></tr><tr><td>Dolorum totam sint debitis saepe laborum.</td><td>Quidem corrupti ea.</td><td>Cum voluptas quod.</td><td>Possimus consequatur quasi dolorem ut et.</td><td>Et velit non hic labore repudiandae quis.</td></tr></tbody></table></body></html>

Modifiers

Faker provides three special providers, unique(), optional(), and valid(), to be called before any provider.

// unique() forces providers to return unique values
$values = array();
for ($i = 0; $i < 10; $i++) {
  // get a random digit, but always a new one, to avoid duplicates
  $values []= $faker->unique()->randomDigit;
}
print_r($values); // [4, 1, 8, 5, 0, 2, 6, 9, 7, 3]

// providers with a limited range will throw an exception when no new unique value can be generated
$values = array();
try {
  for ($i = 0; $i < 10; $i++) {
    $values []= $faker->unique()->randomDigitNotNull;
  }
} catch (\OverflowException $e) {
  echo "There are only 9 unique digits not null, Faker can't generate 10 of them!";
}

// you can reset the unique modifier for all providers by passing true as first argument
$faker->unique($reset = true)->randomDigitNotNull; // will not throw OverflowException since unique() was reset
// tip: unique() keeps one array of values per provider

// optional() sometimes bypasses the provider to return a default value instead (which defaults to NULL)
$values = array();
for ($i = 0; $i < 10; $i++) {
  // get a random digit, but also null sometimes
  $values []= $faker->optional()->randomDigit;
}
print_r($values); // [1, 4, null, 9, 5, null, null, 4, 6, null]

// optional() accepts a weight argument to specify the probability of receiving the default value.
// 0 will always return the default value; 1 will always return the provider. Default weight is 0.5 (50% chance).
$faker->optional($weight = 0.1)->randomDigit; // 90% chance of NULL
$faker->optional($weight = 0.9)->randomDigit; // 10% chance of NULL

// optional() accepts a default argument to specify the default value to return.
// Defaults to NULL.
$faker->optional($weight = 0.5, $default = false)->randomDigit; // 50% chance of FALSE
$faker->optional($weight = 0.9, $default = 'abc')->word; // 10% chance of 'abc'

// valid() only accepts valid values according to the passed validator functions
$values = array();
$evenValidator = function($digit) {
	return $digit % 2 === 0;
};
for ($i = 0; $i < 10; $i++) {
	$values []= $faker->valid($evenValidator)->randomDigit;
}
print_r($values); // [0, 4, 8, 4, 2, 6, 0, 8, 8, 6]

// just like unique(), valid() throws an overflow exception when it can't generate a valid value
$values = array();
try {
  $faker->valid($evenValidator)->randomElement([1, 3, 5, 7, 9]);
} catch (\OverflowException $e) {
  echo "Can't pick an even number in that set!";
}

If you would like to use a modifier with a value not generated by Faker, use the passthrough() method. passthrough() simply returns whatever value it was given.

$faker->optional()->passthrough(mt_rand(5, 15));

Localization

Faker\Factory can take a locale as an argument, to return localized data. If no localized provider is found, the factory fallbacks to the default locale (en_US).

<?php
$faker = Faker\Factory::create('fr_FR'); // create a French faker
for ($i = 0; $i < 10; $i++) {
  echo $faker->name, "\n";
}
  // Luce du Coulon
  // Auguste Dupont
  // Roger Le Voisin
  // Alexandre Lacroix
  // Jacques Humbert-Roy
  // Thérèse Guillet-Andre
  // Gilles Gros-Bodin
  // Amélie Pires
  // Marcel Laporte
  // Geneviève Marchal

You can check available Faker locales in the source code, under the Provider directory. The localization of Faker is an ongoing process, for which we need your help. Don't hesitate to create localized providers to your own locale and submit a PR!

Populating Entities Using an ORM or an ODM

Faker provides adapters for Object-Relational and Object-Document Mappers (currently, Propel, Doctrine2, CakePHP, Spot2, Mandango and Eloquent are supported). These adapters ease the population of databases through the Entity classes provided by an ORM library (or the population of document stores using Document classes provided by an ODM library).

To populate entities, create a new populator class (using a generator instance as parameter), then list the class and number of all the entities that must be generated. To launch the actual data population, call the execute() method.

Note that some of the populators could require additional parameters. As example the doctrine populator has an option to specify its batchSize on how often it will flush the UnitOfWork to the database.

Here is an example showing how to populate 5 Author and 10 Book objects:

<?php
$generator = \Faker\Factory::create();
$populator = new \Faker\ORM\Propel\Populator($generator);
$populator->addEntity('Author', 5);
$populator->addEntity('Book', 10);
$insertedPKs = $populator->execute();

The populator uses name and column type guessers to populate each column with relevant data. For instance, Faker populates a column named first_name using the firstName formatter, and a column with a TIMESTAMP type using the dateTime formatter. The resulting entities are therefore coherent. If Faker misinterprets a column name, you can still specify a custom closure to be used for populating a particular column, using the third argument to addEntity():

<?php
$populator->addEntity('Book', 5, array(
  'ISBN' => function() use ($generator) { return $generator->ean13(); }
));

In this example, Faker will guess a formatter for all columns except ISBN, for which the given anonymous function will be used.

Tip: To ignore some columns, specify null for the column names in the third argument of addEntity(). This is usually necessary for columns added by a behavior:

<?php
$populator->addEntity('Book', 5, array(
  'CreatedAt' => null,
  'UpdatedAt' => null,
));

Of course, Faker does not populate autoincremented primary keys. In addition, Faker\ORM\Propel\Populator::execute() returns the list of inserted PKs, indexed by class:

<?php
print_r($insertedPKs);
// array(
//   'Author' => (34, 35, 36, 37, 38),
//   'Book'   => (456, 457, 458, 459, 470, 471, 472, 473, 474, 475)
// )

Note: Due to the fact that Faker returns all the primary keys inserted, the memory consumption will go up drastically when you do batch inserts due to the big list of data.

In the previous example, the Book and Author models share a relationship. Since Author entities are populated first, Faker is smart enough to relate the populated Book entities to one of the populated Author entities.

Lastly, if you want to execute an arbitrary function on an entity before insertion, use the fourth argument of the addEntity() method:

<?php
$populator->addEntity('Book', 5, array(), array(
  function($book) { $book->publish(); },
));

Seeding the Generator

You may want to get always the same generated data - for instance when using Faker for unit testing purposes. The generator offers a seed() method, which seeds the random number generator. Calling the same script twice with the same seed produces the same results.

<?php
$faker = Faker\Factory::create();
$faker->seed(1234);

echo $faker->name; // 'Jess Mraz I';

Tip: DateTime formatters won't reproduce the same fake data if you don't fix the $max value:

<?php
// even when seeded, this line will return different results because $max varies
$faker->dateTime(); // equivalent to $faker->dateTime($max = 'now')
// make sure you fix the $max parameter
$faker->dateTime('2014-02-25 08:37:17'); // will return always the same date when seeded

Tip: Formatters won't reproduce the same fake data if you use the rand() php function. Use $faker or mt_rand() instead:

<?php
// bad
$faker->realText(rand(10,20));
// good
$faker->realText($faker->numberBetween(10,20));

Faker Internals: Understanding Providers

A Faker\Generator alone can't do much generation. It needs Faker\Provider objects to delegate the data generation to them. Faker\Factory::create() actually creates a Faker\Generator bundled with the default providers. Here is what happens under the hood:

<?php
$faker = new Faker\Generator();
$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));

Whenever you try to access a property on the $faker object, the generator looks for a method with the same name in all the providers attached to it. For instance, calling $faker->name triggers a call to Faker\Provider\Person::name(). And since Faker starts with the last provider, you can easily override existing formatters: just add a provider containing methods named after the formatters you want to override.

That means that you can easily add your own providers to a Faker\Generator instance. A provider is usually a class extending \Faker\Provider\Base. This parent class allows you to use methods like lexify() or randomNumber(); it also gives you access to formatters of other providers, through the protected $generator property. The new formatters are the public methods of the provider class.

Here is an example provider for populating Book data:

<?php

namespace Faker\Provider;

class Book extends \Faker\Provider\Base
{
  public function title($nbWords = 5)
  {
    $sentence = $this->generator->sentence($nbWords);
    return substr($sentence, 0, strlen($sentence) - 1);
  }

  public function ISBN()
  {
    return $this->generator->ean13();
  }
}

To register this provider, just add a new instance of \Faker\Provider\Book to an existing generator:

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

Now you can use the two new formatters like any other Faker formatter:

<?php
$book = new Book();
$book->setTitle($faker->title);
$book->setISBN($faker->ISBN);
$book->setSummary($faker->text);
$book->setPrice($faker->randomNumber(2));

Tip: A provider can also be a Plain Old PHP Object. In that case, all the public methods of the provider become available to the generator.

Real Life Usage

The following script generates a valid XML document:

<?php
require_once '/path/to/Faker/src/autoload.php';
$faker = Faker\Factory::create();
?>
<?xml version="1.0" encoding="UTF-8"?>
<contacts>
<?php for ($i = 0; $i < 10; $i++): ?>
  <contact firstName="<?php echo $faker->firstName ?>" lastName="<?php echo $faker->lastName ?>" email="<?php echo $faker->email ?>">
    <phone number="<?php echo $faker->phoneNumber ?>"/>
<?php if ($faker->boolean(25)): ?>
    <birth date="<?php echo $faker->dateTimeThisCentury->format('Y-m-d') ?>" place="<?php echo $faker->city ?>"/>
<?php endif; ?>
    <address>
      <street><?php echo $faker->streetAddress ?></street>
      <city><?php echo $faker->city ?></city>
      <postcode><?php echo $faker->postcode ?></postcode>
      <state><?php echo $faker->state ?></state>
    </address>
    <company name="<?php echo $faker->company ?>" catchPhrase="<?php echo $faker->catchPhrase ?>">
<?php if ($faker->boolean(33)): ?>
      <offer><?php echo $faker->bs ?></offer>
<?php endif; ?>
<?php if ($faker->boolean(33)): ?>
      <director name="<?php echo $faker->name ?>" />
<?php endif; ?>
    </company>
<?php if ($faker->boolean(15)): ?>
    <details>
<![CDATA[
<?php echo $faker->text(400) ?>
]]>
    </details>
<?php endif; ?>
  </contact>
<?php endfor; ?>
</contacts>

Running this script produces a document looking like:

<?xml version="1.0" encoding="UTF-8"?>
<contacts>
  <contact firstName="Ona" lastName="Bednar" email="[email protected]">
    <phone number="1-265-479-1196x714"/>
    <address>
      <street>182 Harrison Cove</street>
      <city>North Lloyd</city>
      <postcode>45577</postcode>
      <state>Alabama</state>
    </address>
    <company name="Veum, Funk and Shanahan" catchPhrase="Function-based stable solution">
      <offer>orchestrate compelling web-readiness</offer>
    </company>
    <details>
<![CDATA[
Alias accusantium voluptatum autem nobis cumque neque modi. Voluptatem error molestiae consequatur alias.
Illum commodi molestiae aut repellat id. Et sit consequuntur aut et ullam asperiores. Cupiditate culpa voluptatem et mollitia dolor. Nisi praesentium qui ut.
]]>
    </details>
  </contact>
  <contact firstName="Aurelie" lastName="Paucek" email="[email protected]">
    <phone number="863.712.1363x9425"/>
    <address>
      <street>90111 Hegmann Inlet</street>
      <city>South Geovanymouth</city>
      <postcode>69961-9311</postcode>
      <state>Colorado</state>
    </address>
    <company name="Krajcik-Grimes" catchPhrase="Switchable cohesive instructionset">
    </company>
  </contact>
  <contact firstName="Clifton" lastName="Kshlerin" email="[email protected]">
    <phone number="692-194-4746"/>
    <address>
      <street>9791 Nona Corner</street>
      <city>Harberhaven</city>
      <postcode>74062-8191</postcode>
      <state>RhodeIsland</state>
    </address>
    <company name="Rosenbaum-Aufderhar" catchPhrase="Realigned asynchronous encryption">
    </company>
  </contact>
  <contact firstName="Alexandre" lastName="Orn" email="[email protected]">
    <phone number="189.655.8677x027"/>
    <address>
      <street>11161 Schultz Via</street>
      <city>Feilstad</city>
      <postcode>98019</postcode>
      <state>NewJersey</state>
    </address>
    <company name="O'Hara-Prosacco" catchPhrase="Re-engineered solution-oriented algorithm">
      <director name="Dr. Berenice Auer V" />
    </company>
    <details>
<![CDATA[
Ut itaque et quaerat doloremque eum praesentium. Rerum in saepe dolorem. Explicabo qui consequuntur commodi minima rem.
Harum temporibus rerum dolores. Non molestiae id dolorem placeat.
Aut asperiores nihil eius repellendus. Vero nihil corporis voluptatem explicabo commodi. Occaecati omnis blanditiis beatae quod aspernatur eos.
]]>
    </details>
  </contact>
  <contact firstName="Katelynn" lastName="Kohler" email="[email protected]">
    <phone number="(665)713-1657"/>
    <address>
      <street>6106 Nader Village Suite 753</street>
      <city>McLaughlinstad</city>
      <postcode>43189-8621</postcode>
      <state>Missouri</state>
    </address>
    <company name="Herman-Tremblay" catchPhrase="Object-based explicit service-desk">
      <offer>expedite viral synergies</offer>
      <director name="Arden Deckow" />
    </company>
  </contact>
  <contact firstName="Blanca" lastName="Stark" email="[email protected]">
    <phone number="168.719.4692x87177"/>
    <address>
      <street>7546 Kuvalis Plaza</street>
      <city>South Wilfrid</city>
      <postcode>77069</postcode>
      <state>Georgia</state>
    </address>
    <company name="Upton, Braun and Rowe" catchPhrase="Visionary leadingedge pricingstructure">
    </company>
  </contact>
  <contact firstName="Rene" lastName="Spencer" email="[email protected]">
    <phone number="715.222.0095x175"/>
    <birth date="2008-08-07" place="Zulaufborough"/>
    <address>
      <street>478 Daisha Landing Apt. 510</street>
      <city>West Lizethhaven</city>
      <postcode>30566-5362</postcode>
      <state>WestVirginia</state>
    </address>
    <company name="Wiza Inc" catchPhrase="Persevering reciprocal approach">
      <offer>orchestrate dynamic networks</offer>
      <director name="Erwin Nienow" />
    </company>
    <details>
<![CDATA[
Dolorem consequatur voluptates unde optio unde. Accusantium dolorem est est architecto impedit. Corrupti et provident quo.
Reprehenderit dolores aut quidem suscipit repudiandae corporis error. Molestiae enim aperiam illo.
Et similique qui non expedita quia dolorum. Ex rem incidunt ea accusantium temporibus minus non.
]]>
    </details>
  </contact>
  <contact firstName="Alessandro" lastName="Hagenes" email="[email protected]">
    <phone number="1-284-958-6768"/>
    <address>
      <street>1251 Koelpin Mission</street>
      <city>North Revastad</city>
      <postcode>81620</postcode>
      <state>Maryland</state>
    </address>
    <company name="Stiedemann-Bruen" catchPhrase="Re-engineered 24/7 success">
    </company>
  </contact>
  <contact firstName="Novella" lastName="Rutherford" email="[email protected]">
    <phone number="(091)825-7971"/>
    <address>
      <street>6396 Langworth Hills Apt. 446</street>
      <city>New Carlos</city>
      <postcode>89399-0268</postcode>
      <state>Wyoming</state>
    </address>
    <company name="Stroman-Legros" catchPhrase="Expanded 4thgeneration moratorium">
      <director name="Earlene Bayer" />
    </company>
  </contact>
  <contact firstName="Andreane" lastName="Mann" email="[email protected]">
    <phone number="941-659-9982x5689"/>
    <birth date="1934-02-21" place="Stantonborough"/>
    <address>
      <street>2246 Kreiger Station Apt. 291</street>
      <city>Kaydenmouth</city>
      <postcode>11397-1072</postcode>
      <state>Wyoming</state>
    </address>
    <company name="Lebsack, Bernhard and Kiehn" catchPhrase="Persevering actuating framework">
      <offer>grow sticky portals</offer>
    </company>
    <details>
<![CDATA[
Quia dolor ut quia error libero. Enim facilis iusto earum et minus rerum assumenda. Quia doloribus et reprehenderit ut. Occaecati voluptatum dolor voluptatem vitae qui velit quia.
Fugiat non in itaque sunt nobis totam. Sed nesciunt est deleniti cumque alias. Repudiandae quo aut numquam modi dicta libero.
]]>
    </details>
  </contact>
</contacts>

Language specific formatters

Faker\Provider\ar_SA\Person

<?php

echo $faker->idNumber;      // ID number
echo $faker->nationalIdNumber // Citizen ID number
echo $faker->foreignerIdNumber // Foreigner ID number
echo $faker->companyIdNumber // Company ID number

Faker\Provider\ar_SA\Payment

<?php

echo $faker->bankAccountNumber // "SA0218IBYZVZJSEC8536V4XC"

Faker\Provider\at_AT\Payment

<?php

echo $faker->vat;           // "AT U12345678" - Austrian Value Added Tax number
echo $faker->vat(false);    // "ATU12345678" - unspaced Austrian Value Added Tax number

Faker\Provider\bg_BG\Payment

<?php

echo $faker->vat;           // "BG 0123456789" - Bulgarian Value Added Tax number
echo $faker->vat(false);    // "BG0123456789" - unspaced Bulgarian Value Added Tax number

Faker\Provider\cs_CZ\Address

<?php

echo $faker->region; // "Liberecký kraj"

Faker\Provider\cs_CZ\Company

<?php

// Generates a valid IČO
echo $faker->ico; // "69663963"

Faker\Provider\cs_CZ\DateTime

<?php

echo $faker->monthNameGenitive; // "prosince"
echo $faker->formattedDate; // "12. listopadu 2015"

Faker\Provider\cs_CZ\Person

<?php

echo $faker->birthNumber; // "7304243452"

Faker\Provider\da_DK\Person

<?php

// Generates a random CPR number
echo $faker->cpr; // "051280-2387"

Faker\Provider\da_DK\Address

<?php

// Generates a random 'kommune' name
echo $faker->kommune; // "Frederiksberg"

// Generates a random region name
echo $faker->region; // "Region Sjælland"

Faker\Provider\da_DK\Company

<?php

// Generates a random CVR number
echo $faker->cvr; // "32458723"

// Generates a random P number
echo $faker->p; // "5398237590"

Faker\Provider\de_CH\Person

<?php

// Generates a random AVS13/AHV13 social security number
echo $faker->avs13; // "756.1234.5678.97" OR
echo $faker->ahv13; // "756.1234.5678.97"

Faker\Provider\de_DE\Payment

<?php

echo $faker->bankAccountNumber; // "DE41849025553661169313"
echo $faker->bank; // "Volksbank Stuttgart"

Faker\Provider\en_HK\Address

<?php

// Generates a fake town name based on the words commonly found in Hong Kong
echo $faker->town; // "Yuen Long"

// Generates a fake village name based on the words commonly found in Hong Kong
echo $faker->village; // "O Tau"

// Generates a fake estate name based on the words commonly found in Hong Kong
echo $faker->estate; // "Ching Lai Court"

Faker\Provider\en_HK\Phone

<?php

// Generates a Hong Kong mobile number (starting with 5, 6 or 9)
echo $faker->mobileNumber; // "92150087"

// Generates a Hong Kong landline number (starting with 2 or 3)
echo $faker->landlineNumber; // "32750132"

// Generates a Hong Kong fax number (starting with 7)
echo $faker->faxNumber; // "71937729"

Faker\Provider\en_NG\Address

<?php

// Generates a random region name
echo $faker->region; // 'Katsina'

Faker\Provider\en_NG\Person

<?php

// Generates a random person name
echo $faker->name; // 'Oluwunmi Mayowa'

Faker\Provider\en_NZ\Phone

<?php

// Generates a cell (mobile) phone number
echo $faker->mobileNumber; // "021 123 4567"

// Generates a toll free number
echo $faker->tollFreeNumber; // "0800 123 456"

// Area Code
echo $faker->areaCode; // "03"

Faker\Provider\en_US\Company

<?php

// Generate a random Employer Identification Number
echo $faker->ein; // '12-3456789'

Faker\Provider\en_US\Payment

<?php

echo $faker->bankAccountNumber;  // '51915734310'
echo $faker->bankRoutingNumber;  // '212240302'

Faker\Provider\en_US\Person

<?php

// Generates a random Social Security Number
echo $faker->ssn; // '123-45-6789'

Faker\Provider\en_ZA\Company

<?php

// Generates a random company registration number
echo $faker->companyNumber; // 1999/789634/01

Faker\Provider\en_ZA\Person

<?php

// Generates a random national identification number
echo $faker->idNumber; // 6606192211041

// Generates a random valid licence code
echo $faker->licenceCode; // EB

Faker\Provider\en_ZA\PhoneNumber

<?php

// Generates a special rate toll free phone number
echo $faker->tollFreeNumber; // 0800 555 5555

// Generates a mobile phone number
echo $faker->mobileNumber; // 082 123 5555

Faker\Provider\es_ES\Person

<?php

// Generates a Documento Nacional de Identidad (DNI) number
echo $faker->dni; // '77446565E'

// Generates a random valid licence code
echo $faker->licenceCode; // B

Faker\Provider\es_ES\Payment

<?php
// Generates a Código de identificación Fiscal (CIF) number
echo $faker->vat;           // "A35864370"

Faker\Provider\es_ES\PhoneNumber

<?php

// Generates a special rate toll free phone number
echo $faker->tollFreeNumber; // 900 123 456

// Generates a mobile phone number
echo $faker->mobileNumber; // +34 612 12 24

Faker\Provider\es_PE\Person

<?php

// Generates a Peruvian Documento Nacional de Identidad (DNI) number
echo $faker->dni; // '83367512'

Faker\Provider\fa_IR\Person

<?php

// Generates a valid nationalCode
echo $faker->nationalCode; // "0078475759"

Faker\Provider\fa_IR\Address

<?php

// Generates a random building name
echo $faker->building; // "ساختمان آفتاب"

// Returns a random city name
echo $faker->city // "استان زنجان"

Faker\Provider\fa_IR\Company

<?php

// Generates a random contract type
echo $faker->contract; // "رسمی"

Faker\Provider\fi_FI\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "FI8350799879879616"

Faker\Provider\fi_FI\Person

<?php

//Generates a valid Finnish personal identity number (in Finnish - Henkilötunnus)
echo $faker->personalIdentityNumber() // '170974-007J'

//Since the numbers are different for male and female persons, optionally you can specify gender.
echo $faker->personalIdentityNumber(\DateTime::createFromFormat('Y-m-d', '2015-12-14'), 'female') // '141215A520B'

Faker\Provider\fr_BE\Payment

<?php

echo $faker->vat;           // "BE 0123456789" - Belgian Value Added Tax number
echo $faker->vat(false);    // "BE0123456789" - unspaced Belgian Value Added Tax number

Faker\Provider\es_VE\Person

<?php

// Generate a Cédula de identidad number, you can pass one argument to add separator
echo $faker->nationalId; // 'V11223344'

Faker\Provider\es_VE\Company

<?php

// Generates a R.I.F. number, you can pass one argument to add separators
echo $faker->taxpayerIdentificationNumber; // 'J1234567891'

Faker\Provider\fr_CH\Person

<?php

// Generates a random AVS13/AHV13 social security number
echo $faker->avs13; // "756.1234.5678.97"

Faker\Provider\fr_FR\Address

<?php

// Generates a random department name
echo $faker->departmentName; // "Haut-Rhin"

// Generates a random department number
echo $faker->departmentNumber; // "2B"

// Generates a random department info (department number => department name)
$faker->department; // array('18' => 'Cher');

// Generates a random region
echo $faker->region; // "Saint-Pierre-et-Miquelon"

// Generates a random appartement,stair
echo $faker->secondaryAddress; // "Bat. 961"

Faker\Provider\fr_FR\Company

<?php

// Generates a random SIREN number
echo $faker->siren; // 082 250 104

// Generates a random SIRET number
echo $faker->siret; // 347 355 708 00224

Faker\Provider\fr_FR\Payment

<?php

// Generates a random VAT
echo $faker->vat; // FR 12 123 456 789

Faker\Provider\fr_FR\Person

<?php

// Generates a random NIR / Sécurité Sociale number
echo $faker->nir; // 1 88 07 35 127 571 - 19

Faker\Provider\fr_FR\PhoneNumber

<?php

// Generates phone numbers
echo $faker->phoneNumber; // +33 (0)1 67 97 01 31
echo $faker->mobileNumber; // +33 6 21 12 72 84
echo $faker->serviceNumber // 08 98 04 84 46

Faker\Provider\he_IL\Payment

<?php

echo $faker->bankAccountNumber // "IL392237392219429527697"

Faker\Provider\hr_HR\Payment

<?php

echo $faker->bankAccountNumber // "HR3789114847226078672"

Faker\Provider\hu_HU\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "HU09904437680048220079300783"

Faker\Provider\id_ID\Person

<?php

// Generates a random Nomor Induk Kependudukan (NIK)

// first argument is gender, either Person::GENDER_MALE or Person::GENDER_FEMALE, if none specified random gender is used
// second argument is birth date (DateTime object), if none specified, random birth date is used
echo $faker->nik(); // "8522246001570940"

Faker\Provider\it_CH\Person

<?php

// Generates a random AVS13/AHV13 social security number
echo $faker->avs13; // "756.1234.5678.97"

Faker\Provider\it_IT\Company

<?php

// Generates a random Vat Id
echo $faker->vatId(); // "IT98746784967"

Faker\Provider\it_IT\Person

<?php

// Generates a random Tax Id code (Codice fiscale)
echo $faker->taxId(); // "DIXDPZ44E08F367A"

Faker\Provider\ja_JP\Person

<?php

// Generates a 'kana' name
echo $faker->kanaName($gender = null|'male'|'female') // "アオタ ミノル"

// Generates a 'kana' first name
echo $faker->firstKanaName($gender = null|'male'|'female') // "ヒデキ"

// Generates a 'kana' first name on the male
echo $faker->firstKanaNameMale // "ヒデキ"

// Generates a 'kana' first name on the female
echo $faker->firstKanaNameFemale // "マアヤ"

// Generates a 'kana' last name
echo $faker->lastKanaName; // "ナカジマ"

Faker\Provider\ka_GE\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "GE33ZV9773853617253389"

Faker\Provider\kk_KZ\Company

<?php

// Generates an business identification number
echo $faker->businessIdentificationNumber; // "150140000019"

Faker\Provider\kk_KZ\Payment

<?php

// Generates a random bank name
echo $faker->bank; // "Қазкоммерцбанк"

// Generates a random bank account number
echo $faker->bankAccountNumber; // "KZ1076321LO4H6X41I37"

Faker\Provider\kk_KZ\Person

<?php

// Generates an individual identification number
echo $faker->individualIdentificationNumber; // "780322300455"

// Generates an individual identification number based on his/her birth date
echo $faker->individualIdentificationNumber(new \DateTime('1999-03-01')); // "990301300455"

Faker\Provider\ko_KR\Address

<?php

// Generates a metropolitan city
echo $faker->metropolitanCity; // "서울특별시"

// Generates a borough
echo $faker->borough; // "강남구"

Faker\Provider\ko_KR\PhoneNumber

<?php

// Generates a local area phone numer
echo $faker->localAreaPhoneNumber; // "02-1234-4567"

// Generates a cell phone number
echo $faker->cellPhoneNumber; // "010-9876-5432"

Faker\Provider\lt_LT\Payment

<?php

echo $faker->bankAccountNumber // "LT300848876740317118"

Faker\Provider\lv_LV\Person

<?php

// Generates a random personal identity card number
echo $faker->personalIdentityNumber; // "140190-12301"

Faker\Provider\ms_MY\Address

<?php

// Generates a random Malaysian township
echo $faker->township; // "Taman Bahagia"

// Generates a random Malaysian town address with matching postcode and state
echo $faker->townState; // "55100 Bukit Bintang, Kuala Lumpur"

Faker\Provider\ms_MY\Miscellaneous

<?php

// Generates a random vehicle license plate number
echo $faker->jpjNumberPlate; // "WPL 5169"

Faker\Provider\ms_MY\Payment

<?php

// Generates a random Malaysian bank
echo $faker->bank; // "Maybank"

// Generates a random Malaysian bank account number (10-16 digits)
echo $faker->bankAccountNumber; // "1234567890123456"

// Generates a random Malaysian insurance company
echo $faker->insurance; // "AIA Malaysia"

// Generates a random Malaysian bank SWIFT Code
echo $faker->swiftCode; // "MBBEMYKLXXX"

Faker\Provider\ms_MY\Person

<?php

// Generates a random personal identity card (myKad) number
echo $faker->myKadNumber($gender = null|'male'|'female', $hyphen = null|true|false); // "710703471796"

Faker\Provider\ms_MY\PhoneNumber

<?php

// Generates a random Malaysian mobile number
echo $faker->mobileNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "+6012-705 3767"

// Generates a random Malaysian landline number
echo $faker->fixedLineNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "03-7112 0455"

// Generates a random Malaysian voip number
echo $faker->voipNumber($countryCodePrefix = null|true|false, $formatting = null|true|false); // "015-458 7099"

Faker\Provider\ne_NP\Address

<?php

//Generates a Nepali district name
echo $faker->district;

//Generates a Nepali city name
echo $faker->cityName;

Faker\Provider\nl_BE\Payment

<?php

echo $faker->vat;           // "BE 0123456789" - Belgian Value Added Tax number
echo $faker->vat(false);    // "BE0123456789" - unspaced Belgian Value Added Tax number

Faker\Provider\nl_BE\Person

<?php

echo $faker->rrn();         // "83051711784" - Belgian Rijksregisternummer
echo $faker->rrn('female'); // "50032089858" - Belgian Rijksregisternummer for a female

Faker\Provider\nl_NL\Company

<?php

echo $faker->jobTitle; // "Houtbewerker"
echo $faker->vat; // "NL123456789B01" - Dutch Value Added Tax number
echo $faker->btw; // "NL123456789B01" - Dutch Value Added Tax number (alias)

Faker\Provider\nl_NL\Person

<?php

echo $faker->idNumber; // "111222333" - Dutch Personal identification number (BSN)

Faker\Provider\nb_NO\MobileNumber

<?php

// Generates a random Norwegian mobile phone number
echo $faker->mobileNumber; // "+4799988777"
echo $faker->mobileNumber; // "999 88 777"
echo $faker->mobileNumber; // "99988777"

Faker\Provider\nb_NO\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "NO3246764709816"

Faker\Provider\pl_PL\Person

<?php

// Generates a random PESEL number
echo $faker->pesel; // "40061451555"
// Generates a random personal identity card number
echo $faker->personalIdentityNumber; // "AKX383360"
// Generates a random taxpayer identification number (NIP)
echo $faker->taxpayerIdentificationNumber; // '8211575109'

Faker\Provider\pl_PL\Company

<?php

// Generates a random REGON number
echo $faker->regon; // "714676680"
// Generates a random local REGON number
echo $faker->regonLocal; // "15346111382836"

Faker\Provider\pl_PL\Payment

<?php

// Generates a random bank name
echo $faker->bank; // "Narodowy Bank Polski"
// Generates a random bank account number
echo $faker->bankAccountNumber; // "PL14968907563953822118075816"

Faker\Provider\pt_PT\Person

<?php

// Generates a random taxpayer identification number (in portuguese - Número de Identificação Fiscal NIF)
echo $faker->taxpayerIdentificationNumber; // '165249277'

Faker\Provider\pt_BR\Address

<?php

// Generates a random region name
echo $faker->region; // 'Nordeste'

// Generates a random region abbreviation
echo $faker->regionAbbr; // 'NE'

Faker\Provider\pt_BR\PhoneNumber

<?php

echo $faker->areaCode;  // 21
echo $faker->cellphone; // 9432-5656
echo $faker->landline;  // 2654-3445
echo $faker->phone;     // random landline, 8-digit or 9-digit cellphone number

// Using the phone functions with a false argument returns unformatted numbers
echo $faker->cellphone(false); // 74336667

// cellphone() has a special second argument to add the 9th digit. Ignored if generated a Radio number
echo $faker->cellphone(true, true); // 98983-3945 or 7343-1290

// Using the "Number" suffix adds area code to the phone
echo $faker->cellphoneNumber;       // (11) 98309-2935
echo $faker->landlineNumber(false); // 3522835934
echo $faker->phoneNumber;           // formatted, random landline or cellphone (obeying the 9th digit rule)
echo $faker->phoneNumberCleared;    // not formatted, random landline or cellphone (obeying the 9th digit rule)

Faker\Provider\pt_BR\Person

<?php

// The name generator may include double first or double last names, plus title and suffix
echo $faker->name; // 'Sr. Luis Adriano Sepúlveda Filho'

// Valid document generators have a boolean argument to remove formatting
echo $faker->cpf;        // '145.343.345-76'
echo $faker->cpf(false); // '45623467866'
echo $faker->rg;         // '84.405.736-3'
echo $faker->rg(false);  // '844057363'

Faker\Provider\pt_BR\Company

<?php

// Generates a Brazilian formatted and valid CNPJ
echo $faker->cnpj;        // '23.663.478/0001-24'
echo $faker->cnpj(false); // '23663478000124'

Faker\Provider\ro_MD\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "MD83BQW1CKMUW34HBESDP3A8"

Faker\Provider\ro_RO\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "RO55WRJE3OE8X3YQI7J26U1E"

Faker\Provider\ro_RO\Person

<?php

// Generates a random male name prefix/title
echo $faker->prefixMale; // "ing."
// Generates a random female name prefix/title
echo $faker->prefixFemale; // "d-na."
// Generates a random male first name
echo $faker->firstNameMale; // "Adrian"
// Generates a random female first name
echo $faker->firstNameFemale; // "Miruna"


// Generates a random Personal Numerical Code (CNP)
echo $faker->cnp; // "2800523081231"
// Valid option values:
//    $gender: null (random), male, female
//    $dateOfBirth (1800+): null (random), Y-m-d, Y-m (random day), Y (random month and day)
//          i.e. '1981-06-16', '2015-03', '1900'
//    $county: 2 letter ISO 3166-2:RO county codes and B1, B2, B3, B4, B5, B6 for Bucharest's 6 sectors
//    $isResident true/false flag if the person resides in Romania
echo $faker->cnp($gender = null, $dateOfBirth = null, $county = null, $isResident = true);

Faker\Provider\ro_RO\PhoneNumber

<?php

// Generates a random toll-free phone number
echo $faker->tollFreePhoneNumber; // "0800123456"
// Generates a random premium-rate phone number
echo $faker->premiumRatePhoneNumber; // "0900123456"

Faker\Provider\ru_RU\Payment

<?php

// Generates a Russian bank name (based on list of real russian banks)
echo $faker->bank; // "ОТП Банк"

//Generate a Russian Tax Payment Number for Company
echo $faker->inn; //  7813540735

//Generate a Russian Tax Code for Company
echo $faker->kpp; // 781301001

Faker\Provider\sv_SE\Payment

<?php

// Generates a random bank account number
echo $faker->bankAccountNumber; // "SE5018548608468284909192"

Faker\Provider\sv_SE\Person

<?php

//Generates a valid Swedish personal identity number (in Swedish - Personnummer)
echo $faker->personalIdentityNumber() // '950910-0799'

//Since the numbers are different for male and female persons, optionally you can specify gender.
echo $faker->personalIdentityNumber('female') // '950910-0781'

Faker\Provider\tr_TR\Person

<?php

//Generates a valid Turkish identity number (in Turkish - T.C. Kimlik No)
echo $faker->tcNo // '55300634882'

Faker\Provider\zh_CN\Payment

<?php

// Generates a random bank name (based on list of real chinese banks)
echo $faker->bank; // '**建设银行'

Faker\Provider\uk_UA\Payment

<?php

// Generates an Ukraine bank name (based on list of real Ukraine banks)
echo $faker->bank; // "Ощадбанк"

Faker\Provider\zh_TW\Person

<?php

// Generates a random personal identify number
echo $faker->personalIdentityNumber; // A223456789

Faker\Provider\zh_TW\Company

<?php

// Generates a random VAT / Company Tax number
echo $faker->VAT; //23456789

Third-Party Libraries Extending/Based On Faker

License

Faker is released under the MIT License. See the bundled LICENSE file for details.

faker's People

Contributors

aanfarhan avatar ankitpokhrel avatar applestump avatar bazo avatar bessl avatar browner12 avatar carusogabriel avatar dynom avatar foobarquaxx avatar fzaninotto avatar georgeharito avatar igorsantos07 avatar jremes-foss avatar localheinz avatar lsv avatar nineinchnick avatar oittaa avatar okj579 avatar pimjansen avatar pomaxa avatar ppelgrims avatar ronanguilloux avatar softius avatar terite avatar tharoldd avatar timwolla avatar tzhuan avatar vlakoff avatar yerlenzhubangaliyev avatar zachflower avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

faker's Issues

Work in Progress: Dutch Provider

I am going to create a Dutch Provider. If you want to help or have some great resources, feel free to contact me or add a comment below!

This issue will close when a Dutch Provider pull request is posted.

[PHP 5.3.2] Not working

When you run Faker in PHP 5.3.2 you'll get this error:

Fatal error: Call to a member function parse() on a non-object in /www/symfony/vendor/faker/src/Faker/Provider/Name.php on line 23

This is because of the following:

As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.
http://php.net/manual/en/language.oop5.decon.php

The Name provider has a name() method which is the same as the name of the class.

Disable fields in Propel adapter

Hi,

I have a question about Faker and the Propel ORM adapter. How to disable a field of an entity to avoid populate it.
The main problem is to deal with Propel behaviors: specific columns shouldn't be populated by the adapter but by the behavior itself. It doesn't work at the moment..

Regards,
William

Faker uses methods named the same as the class name

Hi

I'm currently working on using Faker for a project using PHP 5.3.2 and I'm running into an issue.

According to this documentation on PHP's constructor, PHP versions < 5.3.3 will use a method named the same as a class if it can not find a __construct method in that class.

This is an issue with Faker as some of the providers have a method in them with the same name as the class, which will cause these versions of PHP to call the method. e.g. the Faker\Provider\Address class has an address() method. It leads to errors such as:

PHP Fatal error: Call to a member function parse() on a non-object in faker/src/Faker/Provider/Address.php on line 91

Defining a __construct method that just calls the parent constructor works, but throws a PHP strict standards notice:

PHP Strict Standards: Redefining already defined constructor for class Faker\Provider\Address in faker/src/Faker/Provider/Address.php on line 93

Is there a solution that allows you to keep your architecture but ignores this php backwards compatibility shim?

Cheers,
Chris.

Remove the circular dependency between generator and provider

Currently a design is chosen that follows the following design principle:

$faker = new Faker\Generator();
$faker->addProvider(new Faker\Provider\en_US\Name($faker));
// ...

This seems like an unnecessary dependency and makes extending Faker more difficult. I would vote to change the design and allow for optional injection and add some logic to test if an alternate provider has been defined:

$faker = new Faker\Generator();
$faker->addProvider(new Faker\Provider\en_US\Name()); // $faker is not passed as argument
// ...

Faker\Generator should be refactored to embrace this change:

class Generator
{
    public function addProvider(\Faker\Provider $provider)
    {
        if ( ! $provider->hasGenerator()) {
            $provider->setGenerator($this);
        }

        // ..
    }

    // ..
}

How to insert Faker data into the database?

I have downloaded the .zip file and given path later i run the file using the browser to check the data is displaying randomly or not. Till now am clear but can any one tell me how to insert the data into my database table.

New tag -> v1.1.1 ?

Last tag is 7 months old. Some useful features have been added to the project (like randomFloat in Base Provider). Time for another tag?

Feature Request: Path to any local file

I need the ability to pick a random image from a local directory.

I am currently playing around with the following idea where you can either pass in a filename pattern as needed by glob() or by passing in a directory and a list of extensions. This will pick a random filename given those parameters.

class FileLocal
{
    public static function fileLocalPattern($pattern)
    {
        $files = glob($pattern, GLOB_BRACE);

        if (count($files) == 0) {
            return false;
        }

        $file = array_rand($files);

        return $files[$file];
    }

    public static function fileLocal($dir, $types = array())
    {
        $pattern = $dir . DIRECTORY_SEPARATOR . '*.{' . implode(',', $types) . '}';

        return static::fileLocalPattern($pattern);
    }
}

It needs tests and this is currently only a local implementation (not as part of a forked Faker, I'm still a little new to GitHub) Would something like this be a useful provider to add?

Is there a "unique" switch?

I'm using Faker with BazingaFakerBundle to populate a database. Some entities have UNIQUE constraints on their fields, for example

table MyCountry
id
name (unique = true)

I'm using the Address provider to insert e.g. 10 countries, but most of the time some country will be inserted twice and the insert fails.

Is there already an easy way to get only unique values from the provider methods?

Documentor & non-API public static methods

I noticed Documentor throws a warning with french locale

Warning: Missing argument 1 for Faker\Provider\fr_FR\Company::isCatchPhraseValid()

The problem is that Documentor parses all the public methods, and isCatchPhraseValid is public static, to make it testable. The warning can be easily removed by adding a default value to the parameter (should I send a pull request for that ??)

public static function isCatchPhraseValid($catchPhrase = '')

BUT isCatchPhraseValid is still returned as an API method by Documentor

I didn't really understand why there is a mix of instance & static public method inside Providers, what is the difference ?

Maybe isCatchPhraseValid shouldn't be exposed as public or moved to another class ?

Unknow formatter : catchPhrase

Since a couple of days, Faker is throwing exceptions.

[InvalidArgumentException] Unknown formatter "catchPhrase"

When using faker as follows :

$faker = Factory::create('fr_FR');
echo $faker->catchPhrase;

Am I missing something?

Executing functions on entities

it seems this is supported just by Propel populator...

<?php
$populator->addEntity('Book', 5, array(), array(
  function($book) { $book->publish(); },
));

Object Mother Support (Fixture Factory)

It seems that Faker could be an exceptional candidate for Fixture Factory support. This was originally made popular by Martin Fowler's Object Mother Pattern and has since been adopted in popular ruby packages like Factory Girl and Object Daddy. Here's a great Blog Post on the benefits of Factories over Fixtures.

There appears to be one such attempt in PHP land, namely in the Xi Project. https://github.com/xi-project/xi-doctrine. See FixtureFactory. Faker already has the ability to create fixtures and has ORM/ODM providers. With a little work, we could provide a very solid Object Mother that makes testing incredibly succinct.

dateTime is not constant

<?php
$faker = Faker\Factory::create();
$faker->seed(1);

echo $faker->dateTime;

This piece of code generates new value for every new day. Is it normal?

Incorrect chars faking localizated emails

Hi,
If I populate emails in Spanish (the same problem will happen in other langs with written accents) y get emails with accents like:

álvaro@...... which is not correct.

I suggest adding something like [^a-zA-Z0-9.-_@] to the email functions in

Faker\Provider\Internet

I am not very good at reg_exp that is why I have not do it by myself.

Sorry and thanks for the help.

Feature Request: Generate human readable texts.... using Public Domain Contents!

Hi,

I LOVE PHP FAKER! It is unbelievably awesome and integrates flawlessly with anything!

Anyways, I really like the bs and catchphrase feature in Faker, especially because they make a lot of sense. Lipsum texts are cool but you just cannot beat human readable texts.

It will be nice if Faker automatically grabbed random contents from public domain ebooks.

Sites like http://www.gutenberg.org/ are great for public domain contents.

So, you shouldn't get in any kind of trouble for using those contents on a script like this.

ipv4 generation issue on 32-bit platform

There is an issue with the code used to generate an ipv4 address. On a 32-bit platform it frequently returns '0.0.0.0' due to the code used in the random number generator.

The code used in Fakers\Provider\Internet.php line 122 is:

return long2ip(mt_rand(-2147483648, 2147483647));

http://php.net/manual/en/function.mt-rand.php#96022 describes the issue: "mt_getrandmax() is NOT the max INTEGER size. It is limited to positive numbers from ZERO to your integers largest value. Thus, it is HALF the size of an INTEGER, since integers are SIGNED, but mt_rand can only correctly randomize from ZERO to mt_getrandmax()."

Therefore using mt_rand(0, 2147483647) works consistently, but only produces half the range. Using mt_rand(-2147483648, 2147483647) produces a large number of '0' values.

One solution might be to use an additional call to generate either a 0 or 1 and use this as a basis for whether to produce a positive or negative number. The following works perfectly every time:

return long2ip(mt_rand(0, 1) == 0 ? mt_rand(-2147483648, 0) : mt_rand(1, 2147483647));

Adding an autoloader

Hi,

What about adding an autoloader for this lib ? And to set a "standard" directory structure as below:

 Faker
    |_ src/
    |    |_  Faker/
    |        |_ Provider/
    |        |_ Factory.php
    |        |_ Generator.php
    |_ tests/
         |_  Faker/
             |_ Provider/
             |_ FactoryTest.php
             |_ GeneratorTest.php

That will follow the PSR-0 standard and will ease integration in other projects. You won't have to provide a dependency with ClassLoader except for unit test or standalone usage (which is more or less the same thing).

See: https://github.com/knplabs/Gaufrette
Note: Propel2 will follow the same standard.

safeEmail is not that safe

Hi there,

the current implementation of safeEmail is not really safe, because of the localized TLDs. The domain example.de in case of Germany is registered to a private artist. As RFC 2606 states the following TLDs are regarded safe for testing and documentation purposes:

  • *.test
  • *.example
  • *.invalid
  • *.localhost

Additionally the following second level domains are reserved as well and therefore are safe:

  • example.com
  • example.net
  • example.org

example.<any other TLD> is not safe!

I can provide a Pull Request if you want. It may take some time, depending how busy I am in the next days, though.

Add support for fake images

With the support of existing API such as Placehold.it or LoremPixel, Faker could easily provide fake pictures/avatars etc which is more and more present in layouts.

new providers

Has anyone created a provider for html or markov chains ?

Html would be handy for wysiwyg editor content for blogs, cms's and comment systems.

A markov generator would be much better for approximation of actual logical content than the random lorem one. Especially for word count statistics and keyword analysis, tagging, search systems etc.

Populating with orm Doctrine not working as expected...

Hi I have a Doctrine Entity like this:

...    
name: {type: string, length: 255}
address: {type: string, length: 255}
phone_number: {type: string, length: 255}
company: {type: string, length: 255}
email: {type: string, length: 255}
url: {type: string, length: 255}
...

When I try to fake on entry with this code

...
$em = $this->getEntityManager();           
$generator = \Faker\Factory::create($locale);
$populator = new \Faker\ORM\Doctrine\Populator($generator, $em);
$populator->addEntity($this->getEntityName(), 1);
$results = $populator->execute();
...

What I get is something like this:

  • name: Aut temporibus nam numquam repudiandae. Placeat quae dolor dolorem dolore placeat rerum. Voluptate praesentium repellendus quaerat illo impedit. (INCORRECT not a $faker->name instance)
  • address: Paseo Angela, 860, 70º C, 07278, Luján del Penedès (CORRECT)
  • phone_number: +34 944-22-3479 (CORRECT)
  • company: Laborum maxime qui sit expedita esse aliquam. Velit quis exercitationem et quas minus. Ut quam ducimus dolorem quia impedit minima qui. Voluptatem ab nemo nam ab. Culpa expedita rerum suscipit aut. Aspernatur delectus qui dolorum est debitis labore. (INCORRECT not a $faker->company instance)
  • email: [email protected] (CORRECT)
  • url: Magni porro totam illum aliquam aut molestias sit maiores. Est reiciendis architecto consequatur laboriosam voluptatum. Sit quo consequatur nemo quaerat ipsum dolor corrupti nihil. (INCORRECT not a $faker->url instance)

I have debug to EntityPopulator fillColumns Method on
https://github.com/fzaninotto/Faker/blob/master/src/Faker/ORM/Doctrine/EntityPopulator.php
And I suppose something is missing/wrong with this line

$value = is_callable($format) ? $format($insertedEntities, $obj) : $format;

But I really cannot follow up. Any ideas?? Thank you in advance.

No Color provider available through composer

Hi,

The alias "dev-master": "1.2.x-dev" in your composer.json still points on the tag 1.2.0 which has no Color provider.

Could you do something about this ?

Thank you in advance,

Regards.

arrayPopulator and/or stcClassPopulator

What about an arrayPopulator or a stcClassPopulator ? I'm using faker for testing purpose and often I need to generate some fake data and the store it in a variable for later use.

Right now I need to manually copy these values from the faker object. Wouldn't be nice to have some kind of populator to solve this problem ?

Am I missing something? Is that already possible with faker ?

Unknown argument "optional"

Today I've updated Faker to it's most recent version using Composer. For some reason, the $faker->optional() method does not work anymore. I have also tried to use it as an object $faker->optional, but that didn't work either.

The error message I get is:

[InvalidArgumentException]
Unkown argument "optional"

I am using Faker in a Laravel 4 application, but that doesn't seem to have anything to do with it. I've tested on both Windows and Mac machines.

Usually I update dependencies once a week, so I expect this problem has been introduced in one of the recent commits.

Idea: image faker

Would it be bad idea to also provide API for faking images? This could easily be done with gd library and would also help when styling webpage with random data in it. What do you think?

Distribute through PEAR

It would be great if I could just install it via pear and Faker is always in my include path.

I know that I can archive this right now by hand, still… this is what pear is for – at least the installer.

Support for the Eloquent ORM

The Laravel framework has been gaining a lot of weight this past year and with the close release of Laravel 4 which will be Composer-ready, it has already imposed itself as one of the top PHP frameworks available. Is there a plan to support its ORM in the roadmap ?
Details on the Eloquent ORM can be found here. I'd gladly work on a PR myself but I would need more details on how Faker handles ORM, I tried peeking into the code but couldn't quite grasp how it's all managed.

Problems with emails in spanish language

Email generation in spanish language use some non valid email chars that are availables in spanish names (ñ, á, é, í, ó, ú).

Emails show be free of this chars because most software apps return as a not valid email.

Regards,
Lito.

Separate male an female first name

I'm working with Faker to populate fixtures and I have an entity with sexe and first name. As firstname provider mixes male and female, I obtain uncoherents datas and I don't know if it would be an interresting add... I'm not very familiar with pull so I'd rather prefer asking.
Anyway, I'm forking your project to work on some more personnal issues.

New localized provider for Serbia

I would like to contribute provider for Serbian locale. But I'm not sure which locale ID I should use.

We have two locales sr_Latn and sr_Cyrl since we use both latin and cyrillic script, so we should have separated providers for this two.

Should it be sr_Latn_RS and sr_Cyrl_RS, or I can go with sr_Latn and sr_Cyrl? Or some other ID, I'm not sure, I usually work with sr_Latn and sr_Cyrl, but I see the format here is language_COUNTRY.

Thoughts?

Invalid UTF-8 sequence in domain provider with the Bulgarian provider

Hi,

I generate a bunch of data with as many providers as possible, to generate a realistic international set. However whenever I use the Bulgarian provider I keep getting invalid utf-8 sequences, like: Йоан-Александър92@���к��е������������.bg

The problem seems to lie with domain generation. This becomes even more clear in the second example.

In hex:

\xd0\x99\xd0\xbe\xd0\xb0\xd0\xbd\x2d\xd0\x90\xd0\xbb\xd0\xb5\xd0\xba\xd1\x81\xd0\xb0\xd0\xbd\xd0\xb4\xd1\x8a\xd1\x80\x39\x32\x40\xd0\xd1\xd1\xd0\xba\xd1\xd0\xd0\xb5\xd0\xd0\xd0\xd0\xd0\xd0\xd0\xd0\xd1\xd0\xd0\xd0\x2e\x62\x67

(\x40 == @)

The definition:

Foo\Entity\EmailAddress:
    mail_bg{1...500}:
        __construct: [ <bg_BG:safeEmail()> ]

Second example:

Foo\Entity\Network
    network_bg{1...5}:
        __construct: [ <bg_BG:company()>, <bg_BG:domainWord()> ]
        subdomain (unique): <bg_BG:domainWord()>

The error

[Doctrine\DBAL\DBALException]
  An exception occurred while executing 'INSERT INTO network (name, subdomain, ...) VALUES (?, ?, ...)' with params ["\u0413\u0430\u0431\u0440\u043e\u0432\u043b\u0438\u0435\u0432\u0430-\u041f\u0435\u043d\u0434\u0436\u0430\u043a\u043e\u0432\u0430", "\xd0\xd0\xd1\xd1\xd0\xd0\xba\xd0\xd0\xd0\xd0", ...]:

  SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xD0\xD0\xD1\xD1\xD0\xD0...' for column 'subdomain' at row 1

The first is the name, a valid sequence. The second is the subdomain name, an invalid sequence.

Something is wrong with Lorem provider

Here are code examples and their outputs:

$faker = \Faker\Factory::create();
var_dump($faker->text(20)); // string(0) "" (expected some text)
$faker = \Faker\Factory::create();
var_dump($faker->sentence(2)); // string(22) "Quos vel odit dolorum."  (expected 2 words sentence)
$faker = \Faker\Factory::create();
var_dump($faker->paragraph(2)); // string(136) "Quasi et qui quos ut veniam sunt. Soluta harum minima aut mollitia libero quae cum. Sapiente dolor ullam eaque voluptatibus aperiam quo." (expected 2 sentence paragraph)

Faker 1.2.* lost unique()

After the recent version bump and a composer update, 1.2.* is currently mapping to the tagged release instead of dev master. The first thing I ran into was that unique() was no longer an option.

Not a bug per se, but it was a bit of a surprise when composer update downgraded Faker. Fixing to 1.3.* gets everything back to normal.

Localized providers

Create a localized provider, and modify the factory to take a locale argument

[Proposal] URL with query params

Currently you have url method that returns something like this:

http://randomsite.com/

Can you add method like urlWithParams (not the best title) that will return something like:

http://anothersite.com/?id=2&aff_id=20&source=banner

or

http://thirdsite.com/forum.php?topic_id=20

I think its gonna be great tool for testing purpose.

Problem with sentences <= 2 words

Hi,
The library may bug when you generate sentences inferior or equal to 2 words ("Undefined offset 0" ).
It comes from the sentence function from the Lorem provider:

<?php
    public static function sentence($nbWords = 6) // if $nbWords <= 2
    {
        $words = static::words($nbWords + mt_rand(-2, 2)); // may return empty array
        $words[0] = ucwords($words[0]); // so this line causes the application to crash

        return join($words, ' ') . '.';
    }

I suspect there is a similar problem with the paragraph function.

There are a couple of ways to deal with these 'problems', that's why I didn't attached any code.
What do you propose? Is it the normal behaviour, should it throws exceptions or should it returns an empty string?

OneToOne relationship doesn't work

If I have OneToOne relationship in Doctrine2, I get error below, because Faker try to assign more entities.

Integrity constraint violation: 1062 Duplicate entry '221' for key

Phaker instead of Faker??

I discovered it today and I can´t stop playing with it, ;). Just lo let you know that phaker could be a cool name. Anyway, don´t pay too much attention to this.

Thank you so much for such a great project.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.