Phinx is a really cool database migration package that allows you to write changes to your database as code. It keeps track of which changes have been applied and allows you the option of rolling back if you hit an issue.
All the documentation on Phinx describes a typical setup where you would run the
phinx command to do your migrations. And that is all fine and good in most projects. But what happens if you are integrating Phinx into an existing project that already has a lot of the usual scaffolding in place?
Why would you want to do this? Maybe this file will be copiled into a Phar so there is no other commands to call. Maybe it uses an internal SQLite database that is persistent. In my case, I am building an application contained in a Docker container that already has
symfony\console and a bunch of console commands. It seems weird to just shell out and run some commands.
But, Phinx is written in PHP. And that means that there is a good chance that there is a way to do it programmatically from within the code we have already written (such as from our existing
It turns out that there is, and it is VERY straightforward. It looks something like this:
use Phinx\Config\Config; use Phinx\Migration\Manager; $base = "/full/path/to/your/root"; $phinx = new Manager( new Config([ 'paths' => [ 'migrations' => "$base/Database/Migrations", 'seeds' => "$base/Database/Seeds", ], 'environments' => [ 'default_migration_table' => 'phinxlog', 'default_database' => 'production', 'production' => [ 'adapter' => $config->get('database.driver'), 'host' => $config->get('database.host'), 'user' => $config->get('database.username'), 'pass' => $config->get('database.password'), 'port' => $config->get('database.port'), 'name' => $config->get('database.database'), 'suffix' => $config->get('database.suffix'), ] ] ]), $input, $output ); // Run any migrations. $phinx->migrate('production');
Want to rollback?
Some notes about this:
OutputInterface. I was already running this from an existing console command so it made sense to just reuse them,
$config->get()is an config fetcher, but I am sure you can see what is going on here.
Basically, the config you write should match the Phinx Yaml file.