Migrations
Forme supports database schema migrations, and uses Phinx under the hood.
What are migrations?
Migrations are a way to keep your database schema configuration within your codebase, and therefore any changes remain within version control. Migration frameworks usually come with some kind of cli and/or automation meaning that you don't need to run any ad hoc SQL or make database changes manually. They also usually provide some kind of abstraction/api so that you don't need write raw SQL.
In WordPress projects we obviously don't need to worry about this when we are using WordPress post types etc, but migrations are useful if we need to create some custom tables and objects for our project.
Writing migrations
Migrations live in app/Database/Migrations
and extend Phinx\Migration\AbstractMigration
. The file name format should be YYYYMMDDHHMMSS_my_new_migration.php
, where the first 14 characters are replaced with the current timestamp down to the second.
They normally have a single method change
, in which you define the schema changes.
// app/Database/Migrations/20201209100327_create_user_logins_table.php
<?php
declare(strict_types=1);
namespace YourNameSpace\YourApp\Database\Migrations;
use Phinx\Migration\AbstractMigration;
class CreateUserLoginsTable extends AbstractMigration
{
public function change(): void
{
// create the table
$table = $this->table('user_logins');
$table->addColumn('user_id', 'integer')
->addColumn('created', 'datetime')
->create();
}
}
You can check the phinx docs for info on how to work with the table object.
TIP
You should use the code generation cli to create migration files as it will name them properly for you.
Running Migrations
Migrations run automatically on plugin or theme activation. This process also takes care of the phinx configuration for you.
You can alternatively trigger migrations directly via the phinx cli, but this will only work once the configuration exists, in other words once the activation of your plugin or theme has happened at least once within your project.
# Run this from the FORME_PRIVATE_ROOT directory
vendor/bin/phinx migrate
TIP
The configuration file lives in FORME_PRIVATE_ROOT/phinx.yml
. If you need to, you can generate it yourself and/or edit it manually, but we won't go into that here (check the phinx docs for more information). Bear in mind that it is likely to get automatically updated and written over during plugin/theme activation, so YMMV.
Code Generation
You can use the cli to create a blank migration.
forme make migration FooBar
This will create a new suitably named migration file for you in app/Database/Migrations
.