Faker, the PHP fake data generator, already knows how to populate a database using an ORM. As explained in an earlier post, the metadata provided to the ORM is often sufficient to qualify the formatter required for each column. So for instance, to populate 3 records in an
author table with
\Faker\ORM\Propel\Populator class guesses the formatters to use for each column based on their name and/or column type.
However, if you look carefully at the generated data, it's not consistent. Because the email is generated independently of the name, it doesn't seem to relate to the same person. In order to generate consistent data, you should be able to modify the email fake data yourself.
That's why Faker allows you to specify custom column formatters using the third parameter of the
But what if you need to access the object itself during generation, instead of a single column? For instance, the
Author model can use the
sortable behavior to keep the authors in order of preference. In order to generate a consistent (and properly ordered) set of authors, each new
Author object must be inserted at a random position in the list. This is made possible thanks to the custom modifiers parameter, the fourth of the
Just as it knows which formatters to use based on column metadata, Faker also guesses the custom formatters to apply to an entity populator based on the behaviors used by the entity. That means that, since the
Author model uses the Propel
sortable behavior, the custom modifier is not even necessary: Faker will generate fake
Author instances with consistent sorting on its own:
Faker currently implements custom modifiers for the
nested_set behaviors. Besides, the
sluggable behaviors need no specific modifier and work out of the box within Faker.
Published on 28 Apr 2012
with tags faker