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:

$ php bin/phinx create CreateUserTable

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

Then use the migrate command to execute the migration:

$ php bin/phinx migrate -e development

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:

$ php bin/phinx seed:create UserSeeder

Now open the file and paste the following code:

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

$ php vendor/bin/phinx seed:run -e development

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:

$ composer require fzaninotto/faker

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

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:

$ php vendor/bin/phinx seed:run -e development -s UserSeeder

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.

Rob Morgan

CTO based in Berlin, Germany. Creator of #Phinx, Australian, Startups, Technology, Travel.

robmorgan _rjm_


Published