You’re building an application, and you need to share the database’s structure with your team. After all, you want everyone to be up and running as soon as possible. What do you do? SQL dumps of table structures? You could… but that’s so very primitive – and can be time consuming to import, too! More often than not, database migrations are the answer.
In this tutorial, we’ll go through a framework-agnostic package for building and executing database migrations called Phinx.
First, let’s install Phinx into the project with Composer:
composer require robmorgan/phinx
The Phinx binary will be installed into the
vendor/bin folder, as per Composer’s default values. It can then be executed by running:
Phinx needs a
phinx.yml file from which to read the database configuration before it can do anything meaningful. To generate it, we run:
php vendor/bin/phinx init
The generate file will look something like this:
paths: migrations: %%PHINX_CONFIG_DIR%%/db/migrations seeds: %%PHINX_CONFIG_DIR%%/db/seeds environments: default_migration_table: phinxlog default_database: development production: adapter: mysql host: localhost name: production_db user: root pass: '' port: 3306 charset: utf8 development: adapter: mysql host: localhost name: development_db user: root pass: '' port: 3306 charset: utf8 testing: adapter: mysql host: localhost name: testing_db user: root pass: '' port: 3306 charset: utf8
Phinx supports an arbitrary number of “databases”, though these should be considered version of one database rather than several different ones. Sometimes, the need may arise to use a completely different database, however.
Such is the case, for example, with nofw, which in a previous version still uses Gatekeeper – a secure but clumsily developed user authorization package. Gatekeeper demands its own
phinx.yml file (with a custom migration path) and does not provide an option to change which one is used, while at the same time requiring its own user database. That throws a wrench into the whole “let’s use Phinx in a project already using Gatekeeper” idea.
For cases like these, Phinx offers the
-c option which tells the launcher which
phinx.yml file to use. Note that Phinx supports
php file formats, too, but we’ll focus on the default
yml one here and create a separate file for our example database.
Continue reading %Phinx – the Migration Library You Never Knew You Needed%