Working with Phinx Seeders & Faker

2 min read
phpphinxmigrationsseeding

Yesterday we shipped Phinx 0.5.0 with the long awaited seed feature. This was a substantial release as it required quite a few internal changes as well as downstream changes to dependent projects such as CakePHP. Today I'm going to give a brief overview of the seed feature.

Seeders are great for quickly filling your database with test data. You simply run your migrations first to create the database then execute the seed:run command.

Locally I'm developing a hypothetical web application and I'll need a table to store the users in. I'm assuming you've already setup a basic web application and installed Phinx. To create a new migration, simply run:

Now lets use the migration to create a table, copy this code:

gist:robmorgan/8b293646a14b9c6c9c81#20151129162222_create_user_table.php

Then use the migrate command to execute the migration:

Great, now we can use the seed commands to insert some test data into the new table. First start by creating a new seed class:

Now open the file and paste the following code:

gist:robmorgan/8b293646a14b9c6c9c81#UserSeeder.php

Let's execute our seeder to insert a database record:

Note: Unlike migrations Phinx does not keep track of which seeders have been run, keep this in mind when writing them. They should be able to be run repeatedly.

What's even cooler is that it's trivial to integrate the awesome Faker library. Simply install Faker using Composer:

And then let's rewrite the UserSeeder class to use it:

gist:robmorgan/8b293646a14b9c6c9c81#UserSeeder2.php

Now when we re-execute the same seeder, Faker will generate 100 dummy users. By default Phinx runs all available seeders however I'll use the -s parameter to demonstrate just running one:

In Conclusion

You've now created and executed your first Phinx database seeder. I hope you find the new feature useful. Please remember to report any bugs or feature requests using the Phinx issue tracker. More information about the seed feature is available in the official Phinx documentation.