Phinx Documentation Release 0.4.1 Rob Morgan

Transcription

Phinx Documentation Release 0.4.1 Rob Morgan
Phinx Documentation
Release 0.4.2.1
Rob Morgan
February 07, 2015
Contents
1
2
Contents
1.1 Introduction . . .
1.2 Goals . . . . . . .
1.3 Installation . . . .
1.4 Writing Migrations
1.5 Commands . . . .
1.6 Configuration . . .
1.7 Copyright . . . . .
Indices and tables
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
3
3
3
3
4
18
20
23
25
i
ii
Phinx Documentation, Release 0.4.2.1
Phinx makes it ridiculously easy to manage the database migrations for your PHP app. In less than 5 minutes you can
install Phinx using Composer and create your first database migration. Phinx is just about migrations without all the
bloat of a database ORM system or application framework.
Contents
1
Phinx Documentation, Release 0.4.2.1
2
Contents
CHAPTER 1
Contents
1.1 Introduction
Good developers always version their code using a SCM system, so why don’t they do the same for their database
schema?
Phinx allows developers to alter and manipulate databases in a clear and concise way. It avoids the use of writing
SQL by hand and instead offers a powerful API for creating migrations using PHP code. Developers can then version
these migrations using their preferred SCM system. This makes Phinx migrations portable between different database
systems. Phinx keeps track of which migrations have been run so you can worry less about the state of your database
and instead focus on building better software.
1.2 Goals
Phinx was developed with the following goals in mind:
• Be portable amongst the most popular database vendors.
• Be PHP framework independent.
• Have a simple install process.
• Have an easy to use command-line operation.
• Integrate with various other PHP tools (Phing, PHPUnit) and web frameworks.
1.3 Installation
Phinx should be installed using Composer. Composer is a tool for dependency management in PHP. Please visit the
Composer website for more information.
Note: Phinx requires at least PHP 5.3.2 (or later).
To install Phinx, simply require it using Composer:
php composer.phar require robmorgan/phinx
Then run Composer:
3
Phinx Documentation, Release 0.4.2.1
php composer.phar install --no-dev
Create a folder in your project directory called migrations with adequate permissions. It is where your migration
files will live and should be writable.
Phinx can now be executed from within your project:
php vendor/bin/phinx init
1.4 Writing Migrations
Phinx relies on migrations in order to transform your database. Each migration is represented by a PHP class in a
unique file. It is preferred that you write your migrations using the Phinx PHP API, but raw SQL is also supported.
1.4.1 Creating a New Migration
Let’s start by creating a new Phinx migration. Run Phinx using the create command:
$ phinx create MyNewMigration
This will create a new migration in the format YYYYMMDDHHMMSS_my_new_migration.php where the first 14
characters are replaced with the current timestamp down to the second.
Phinx automatically creates a skeleton migration file with two empty methods and a commented out one:
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
*
* Uncomment this method if you would like to use it.
*
public function change()
{
}
*/
/**
* Migrate Up.
*/
public function up()
{
}
/**
* Migrate Down.
*/
public function down()
4
Chapter 1. Contents
Phinx Documentation, Release 0.4.2.1
{
}
}
1.4.2 The AbstractMigration Class
All Phinx migrations extend from the AbstractMigration class. This class provides the necessary support to
create your database migrations. Database migrations can transform your database in many ways such as creating new
tables, inserting rows, adding indexes and modifying columns.
The Up Method
The up method is automatically run by Phinx when you are migrating up and it detects the given migration hasn’t been
executed previously. You should use the up method to transform the database with your intended changes.
The Down Method
The down method is automatically run by Phinx when you are migrating down and it detects the given migration has
been executed in the past. You should use the down method to reverse/undo the transformations described in the up
method.
The Change Method
Phinx 0.2.0 introduced a new feature called reversible migrations. With reversible migrations you only need to define
the up logic and Phinx can figure out how to migrate down automatically for you. To define a reversible migration
you must uncomment the change method in your migration file. For example:
<?php
use Phinx\Migration\AbstractMigration;
class CreateUserLoginsTable extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
*
* Uncomment this method if you would like to use it.
*/
public function change()
{
// create the table
$table = $this->table(’user_logins’);
$table->addColumn(’user_id’, ’integer’)
->addColumn(’created’, ’datetime’)
->create();
}
/**
* Migrate Up.
1.4. Writing Migrations
5
Phinx Documentation, Release 0.4.2.1
*/
public function up()
{
}
/**
* Migrate Down.
*/
public function down()
{
}
}
When executing this migration Phinx will create the user_logins table on the way up and automatically figure out
how to drop the table on the way down. Please be aware that when a change method exists Phinx will automatically
ignore the up and down methods. If you need to use these methods it is recommended to create a separate migration
file.
Note: When creating or updating tables inside a change() method you must use the Table create() and
update() methods. Phinx cannot automatically determine whether a save() call is creating a new table or modifying an existing one.
Phinx can only reverse the following commands:
• createTable
• renameTable
• addColumn
• renameColumn
• addIndex
• addForeignKey
If a command cannot be reversed then Phinx will throw a IrreversibleMigrationException exception when
it’s migrating down.
1.4.3 Executing Queries
Queries can be executed with the execute() and query() methods. The execute() method returns the number
of affected rows whereas the query() method returns the result as an array.
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
// execute()
$count = $this->execute(’DELETE FROM users’); // returns the number of affected rows
6
Chapter 1. Contents
Phinx Documentation, Release 0.4.2.1
// query()
$rows = $this->query(’SELECT * FROM users’); // returns the result as an array
}
/**
* Migrate Down.
*/
public function down()
{
}
}
Note: These commands run using the PHP Data Objects (PDO) extension which defines a lightweight, consistent interface for accessing databases in PHP. Always make sure your queries abide with PDOs before using the execute()
command. This is especially important when using DELIMITERs during insertion of stored procedures or triggers
which don’t support DELIMITERs.
1.4.4 Fetching Rows
There are two methods available to fetch rows. The fetchRow() method will fetch a single row, whilst the
fetchAll() method will return multiple rows. Both methods accept raw SQL as their only parameter.
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
// fetch a user
$row = $this->fetchRow(’SELECT * FROM users’);
// fetch an array of messages
$rows = $this->fetchAll(’SELECT * FROM messages’);
}
/**
* Migrate Down.
*/
public function down()
{
}
}
1.4. Writing Migrations
7
Phinx Documentation, Release 0.4.2.1
1.4.5 Working With Tables
The Table Object
The Table object is one of the most useful APIs provided by Phinx. It allows you to easily manipulate database tables
using PHP code. You can retrieve an instance of the Table object by calling the table() method from within your
database migration.
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$table = $this->table(’tableName’);
}
/**
* Migrate Down.
*/
public function down()
{
}
}
You can then manipulate this table using the methods provided by the Table object.
Creating a Table
Creating a table is really easy using the Table object. Let’s create a table to store a collection of users.
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$users = $this->table(’users’);
$users->addColumn(’username’, ’string’, array(’limit’ => 20))
->addColumn(’password’, ’string’, array(’limit’ => 40))
->addColumn(’password_salt’, ’string’, array(’limit’ => 40))
->addColumn(’email’, ’string’, array(’limit’ => 100))
->addColumn(’first_name’, ’string’, array(’limit’ => 30))
->addColumn(’last_name’, ’string’, array(’limit’ => 30))
->addColumn(’created’, ’datetime’)
->addColumn(’updated’, ’datetime’, array(’null’ => true))
8
Chapter 1. Contents
Phinx Documentation, Release 0.4.2.1
->addIndex(array(’username’, ’email’), array(’unique’ => true))
->save();
}
/**
* Migrate Down.
*/
public function down()
{
}
}
Columns are added using the addColumn() method. We create a unique index for both the username and email
columns using the addIndex() method. Finally calling save() commits the changes to the database.
Note: Phinx automatically creates an auto-incrementing primary key column called id for every table.
To specify an alternate primary key you can specify the primary_key option when accessing the Table object. Let’s
disable the automatic id column and create a primary key using two columns instead:
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$table = $this->table(’followers’, array(’id’ => false, ’primary_key’ => array(’user_id’, ’fo
$table->addColumn(’user_id’, ’integer’)
->addColumn(’follower_id’, ’integer’)
->addColumn(’created’, ’datetime’)
->save();
}
/**
* Migrate Down.
*/
public function down()
{
}
}
Setting a single primary_key doesn’t enable the AUTO_INCREMENT option. To do this, we need to override the
default id field name:
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
1.4. Writing Migrations
9
Phinx Documentation, Release 0.4.2.1
* Migrate Up.
*/
public function up()
{
$table = $this->table(’followers’, array(’id’ => ’user_id’));
$table->addColumn(’user_id’, ’integer’)
->addColumn(’follower_id’, ’integer’)
->addColumn(’created’, ’datetime’, array(’default’ => ’CURRENT_TIMESTAMP’))
->save();
}
/**
* Migrate Down.
*/
public function down()
{
}
}
Valid Column Types
Column types are specified as strings and can be one of:
• string
• text
• integer
• biginteger
• float
• decimal
• datetime
• timestamp
• time
• date
• binary
• boolean
In addition, the MySQL adapter supports enum and set column types.
In addition, the Postgres adapter supports json and uuid column types (PostgreSQL 9.3 and above).
For valid options, see the Valid Column Options below.
Determining Whether a Table Exists
You can determine whether or not a table exists by using the hasTable() method.
<?php
use Phinx\Migration\AbstractMigration;
10
Chapter 1. Contents
Phinx Documentation, Release 0.4.2.1
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$exists = $this->hasTable(’users’);
if ($exists) {
// do something
}
}
/**
* Migrate Down.
*/
public function down()
{
}
}
Dropping a Table
Tables can be dropped quite easily using the dropTable() method. It is a good idea to recreate the table again in
the down() method.
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$this->dropTable(’users’);
}
/**
* Migrate Down.
*/
public function down()
{
$users = $this->table(’users’);
$users->addColumn(’username’, ’string’, array(’limit’ => 20))
->addColumn(’password’, ’string’, array(’limit’ => 40))
->addColumn(’password_salt’, ’string’, array(’limit’ => 40))
->addColumn(’email’, ’string’, array(’limit’ => 100))
->addColumn(’first_name’, ’string’, array(’limit’ => 30))
->addColumn(’last_name’, ’string’, array(’limit’ => 30))
->addColumn(’created’, ’datetime’)
->addColumn(’updated’, ’datetime’, array(’null’ => true))
->addIndex(array(’username’, ’email’), array(’unique’ => true))
->save();
1.4. Writing Migrations
11
Phinx Documentation, Release 0.4.2.1
}
}
Renaming a Table
To rename a table access an instance of the Table object then call the rename() method.
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$table = $this->table(’users’);
$table->rename(’legacy_users’);
}
/**
* Migrate Down.
*/
public function down()
{
$table = $this->table(’legacy_users’);
$table->rename(’users’);
}
}
Working With Columns
Renaming a Column
To rename a column access an instance of the Table object then call the renameColumn() method.
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$table = $this->table(’users’);
$table->renameColumn(’bio’, ’biography’);
}
/**
* Migrate Down.
*/
12
Chapter 1. Contents
Phinx Documentation, Release 0.4.2.1
public function down()
{
$table = $this->table(’users’);
$table->renameColumn(’biography’, ’bio’);
}
}
Adding a Column After Another Column
When adding a column you can dictate it’s position using the after option.
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Change Method.
*/
public function change()
{
$table = $this->table(’users’);
$table->addColumn(’city’, ’string’, array(’after’ => ’email’))
->update();
}
}
Specifying a Column Limit
You can limit the maximum length of a column by using the limit option.
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Change Method.
*/
public function change()
{
$table = $this->table(’tags’);
$table->addColumn(’short_name’, ’string’, array(’limit’ => 30))
->update();
}
}
Working with Indexes
To add an index to a table you can simply call the addIndex() method on the table object.
1.4. Writing Migrations
13
Phinx Documentation, Release 0.4.2.1
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$table = $this->table(’users’);
$table->addColumn(’city’, ’string’)
->addIndex(array(’city’))
->save();
}
/**
* Migrate Down.
*/
public function down()
{
}
}
By default Phinx instructs the database adapter to create a normal index. We can pass an additional parameter to the
addIndex() method to specify a unique index.
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$table = $this->table(’users’);
$table->addColumn(’email’, ’string’)
->addIndex(array(’email’), array(’unique’ => true))
->save();
}
/**
* Migrate Down.
*/
public function down()
{
}
}
Removing indexes is as easy as calling the removeIndex() method. You must call this method for each index.
<?php
14
Chapter 1. Contents
Phinx Documentation, Release 0.4.2.1
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$table = $this->table(’users’);
$table->removeIndex(array(’email’));
}
/**
* Migrate Down.
*/
public function down()
{
}
}
Note: There is no need to call the save() method when using removeIndex(). The index will be removed
immediately.
Working With Foreign Keys
Phinx has support for creating foreign key constraints on your database tables. Let’s add a foreign key to an example
table:
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$table = $this->table(’tags’);
$table->addColumn(’tag_name’, ’string’)
->save();
$refTable = $this->table(’tag_relationships’);
$refTable->addColumn(’tag_id’, ’integer’)
->addForeignKey(’tag_id’, ’tags’, ’id’, array(’delete’=> ’SET_NULL’, ’update’=> ’NO_
->save();
}
/**
* Migrate Down.
*/
public function down()
1.4. Writing Migrations
15
Phinx Documentation, Release 0.4.2.1
{
}
}
“On delete” and “On update” actions are defined with a ‘delete’ and ‘update’ options array. Possibles values are
‘SET_NULL’, ‘NO_ACTION’, ‘CASCADE’ and ‘RESTRICT’.
We can also easily check if a foreign key exists:
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$table = $this->table(’tag_relationships’);
$exists = $table->hasForeignKey(’tag_id’);
if ($exists) {
// do something
}
}
/**
* Migrate Down.
*/
public function down()
{
}
}
Finally to delete a foreign key use the dropForeignKey method.
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$table = $this->table(’tag_relationships’);
$table->dropForeignKey(’tag_id’);
}
/**
* Migrate Down.
*/
public function down()
{
16
Chapter 1. Contents
Phinx Documentation, Release 0.4.2.1
}
}
Valid Column Options
The following are valid column options:
For any column type:
Option
limit
length
default
null
after
comment
Description
set maximum length for strings, also hints column types in adapters (see note below)
alias for limit
set default value or action
allow NULL values (should not be used with primary keys!)
specify the column that a new column should be placed after
set a text comment on the column
For decimal columns:
Option
precision
scale
Description
combine with scale set to set decimial accuracy
combine with precision to set decimial accuracy
For enum and set columns:
Option
values
Description
Can be a comma separated list or an array of values
For integer and biginteger columns:
Option
identity
signed
Description
enable or disable automatic incrementing
enable or disable the unsigned option (only applies to MySQL)
For timestamp columns:
Option
default
update
timezone
Description
set default value (use with CURRENT_TIMESTAMP)
set an action to be triggered when the row is updated (use with CURRENT_TIMESTAMP)
enable or disable the with time zone option for time and timestamp columns (only applies
to Postgres)
For foreign key definitions:
Option
update
delete
Description
set an action to be triggered when the row is updated
set an action to be triggered when the row is deleted
You can pass one or more of these options to any column with the optional third argument array.
Limit Option and MySQL
When using the MySQL adapter, additional hinting of database column type can be made for integer and text
columns. Using limit with one the following options will modify the column type accordingly:
1.4. Writing Migrations
17
Phinx Documentation, Release 0.4.2.1
Limit
TEXT_TINY
TEXT_REGULAR
TEXT_MEDIUM
TEXT_LONG
INT_TINY
INT_SMALL
INT_MEDIUM
INT_REGULAR
INT_BIG
Column Type
TINYTEXT
TEXT
MEDIUMTEXT
LONGTEXT
TINYINT
SMALLINT
MEDIUMINT
INT
BIGINT
use Phinx\Db\Adapter\MysqlAdapter;
//...
$table = $this->table(’cart_items’);
$table->addColumn(’user_id’, ’integer’)
->addColumn(’product_id’, ’integer’, array(’limit’ => MysqlAdapter::INT_BIG))
->addColumn(’subtype_id’, ’integer’, array(’limit’ => MysqlAdapter::INT_SMALL))
->addColumn(’quantity’, ’integer’, array(’limit’ => MysqlAdapter::INT_TINY))
->create();
The Save Method
When working with the Table object Phinx stores certain operations in a pending changes cache.
When in doubt it is recommended you call this method. It will commit any pending changes to the database.
1.5 Commands
Phinx is run using a number of commands.
1.5.1 The Create Command
The Create command is used to create a new migration file. It requires one argument and that is the name of the
migration. The migration name should be specified in CamelCase format.
$ phinx create MyNewMigration
Open the new migration file in your text editor to add your database transformations. Phinx creates migration files
using the path specified in your phinx.yml file. Please see the Configuration chapter for more information.
You are able to override the template file used by Phinx by supplying an alternative template filename.
$ phinx create MyNewMigration --template="<file>"
You can also supply a template generating
Phinx\Migration\CreationInterface.
class.
This
class
must
implement
the
interface
$ phinx create MyNewMigration --class="<class>"
In addition to providing the template for the migration, the class can also define a callback that will be called once the
migration file has been generated from the template.
You cannot use --template and --class together.
18
Chapter 1. Contents
Phinx Documentation, Release 0.4.2.1
1.5.2 The Init Command
The Init command (short for initialize) is used to prepare your project for Phinx. This command generates the
phinx.yml file in the root of your project directory.
$ cd yourapp
$ phinx init .
Open this file in your text editor to setup your project configuration. Please see the Configuration chapter for more
information.
1.5.3 The Migrate Command
The Migrate command runs all of the available migrations, optionally up to a specific version.
$ phinx migrate -e development
To migrate to a specific version then use the --target parameter or -t for short.
$ phinx migrate -e development -t 20110103081132
1.5.4 The Rollback Command
The Rollback command is used to undo previous migrations executed by Phinx. It is the opposite of the Migrate
command.
You can rollback to the previous migration by using the rollback command with no arguments.
$ phinx rollback -e development
To rollback all migrations to a specific version then use the --target parameter or -t for short.
$ phinx rollback -e development -t 20120103083322
Specifying 0 as the target version will revert all migrations.
$ phinx rollback -e development -t 0
1.5.5 The Status Command
The Status command prints a list of all migrations, along with their current status. You can use this command to
determine which migrations have been run.
$ phinx status -e development
1.5.6 Configuration File Parameter
When running Phinx from the command line, you may specify a configuration file using the --configuration or
-c parameter. In addition to YAML, the configuration file may be the computed output of a PHP file as a PHP array:
<?php
return array(
"paths" => array(
"migrations" => "application/migrations"
1.5. Commands
19
Phinx Documentation, Release 0.4.2.1
),
"environments" => array(
"default_migration_table" => "phinxlog",
"default_database" => "dev",
"dev" => array(
"adapter" => "mysql",
"host" => $_ENV[’DB_HOST’],
"name" => $_ENV[’DB_NAME’],
"user" => $_ENV[’DB_USER’],
"pass" => $_ENV[’DB_PASS’],
"port" => $_ENV[’DB_PORT’]
)
)
);
Phinx auto-detects which language parser to use for files with *.yml and *.php extensions. The appropriate parser
may also be specified via the --parser and -p parameters. Anything other than "php" is treated as YAML.
In case with PHP array you can provide connection key with existing PDO instance to use omitting other parameters:
<?php
return array(
"paths" => array(
"migrations" => "application/migrations"
),
"environments" => array(
"default_migration_table" => "phinxlog",
"default_database" => "dev",
"dev" => array(
"connection" => $pdo_instance
)
)
);
1.5.7 Running Phinx in a Web App
Phinx can also be run inside of a web application by using the Phinx\Wrapper\TextWrapper class. An example
of this is provided in app/web.php, which can be run as a standalone server:
$ php -S localhost:8000 vendor/robmorgan/phinx/app/web.php
This will create local web server at http://localhost:8000 which will show current migration status by default. To run
migrations up, use http://localhost:8000/migrate and to rollback use http://localhost:8000/rollback.
The included web app is only an example and should not be used in production!
Note: To modify configuration variables at runtime and overrid %%PHINX_DBNAME%% or other another dynamic
option, set $_SERVER[’PHINX_DBNAME’] before running commands. Available options are documented in the
Configuration page.
1.6 Configuration
Phinx uses the YAML data serialization format to store it’s configuration data. When you initialize your project using
the Init Command, Phinx creates a file called phinx.yml in the root of your project directory.
20
Chapter 1. Contents
Phinx Documentation, Release 0.4.2.1
Warning: Remember to store the phinx.yml file outside of a publicly accessible directory on your webserver.
This file contains your database credentials and may be accidentally served as plain text.
If you do not wish to use the default configuration file, you may specify a configuration file (or a file that generates a
PHP array) on the command line. See the Commands chapter for more information.
1.6.1 Migration Path
The
first
option
specifies
the
path
to
%%PHINX_CONFIG_DIR%%/migrations by default.
your
migration
directory.
Phinx
uses
Note: %%PHINX_CONFIG_DIR%% is a special token and is automatically replaced with the root directory where
your phinx.yml file is stored.
In order to overwrite the default %%PHINX_CONFIG_DIR%%/migrations, you need to add the following to the
yaml configuration.
paths:
migrations: /your/full/path
You can also use the %%PHINX_CONFIG_DIR%% token in your path.
paths:
migrations: %%PHINX_CONFIG_DIR%%/your/relative/path
1.6.2 Custom Migration Base
By default all migrations will extend from Phinx’s AbstractMigration class. This can be set to a custom class that
extends from AbstractMigration by setting migration_base_class in your config:
migration_base_class: MyMagicalMigration
1.6.3 Environments
One of the key features of Phinx is support for multiple database environments. You can use Phinx to create migrations
on your development environment, then run the same migrations on your production environment. Environments are
specified under the environments nested collection. For example:
environments:
default_migration_table: phinxlog
default_database: development
production:
adapter: mysql
host: localhost
name: production_db
user: root
pass: ’’
port: 3306
charset: utf8
collation: utf8_unicode_ci
would define a new environment called production.
1.6. Configuration
21
Phinx Documentation, Release 0.4.2.1
In a situation when multiple developers work on the same project and each has a different environment
(e.g. a convention such as <environment type>-<developer name>-<machine name>), or when
you need to have separate environments for separate purposes (branches, testing, etc) use environment variable
PHINX_ENVIRONMENT to override the default environment in the yaml file:
export PHINX_ENVIRONMENT=dev-‘whoami‘-‘hostname‘
1.6.4 Socket Connections
When using the MySQL adapter, it is also possible to use sockets instead of network connections. The socket path is
configured with unix_socket:
environments:
default_migration_table: phinxlog
default_database: development
production:
adapter: mysql
name: production_db
user: root
pass: ’’
unix_socket: /var/run/mysql/mysql.sock
charset: utf8
1.6.5 External Variables
Phinx will automatically grab any environment variable prefixed with PHINX_ and make it available as a token in the
config file. The token will have exactly the same name as the variable but you must access it by wrapping two %%
symbols on either side. e.g: %%PHINX_DBUSER%%. This is especially useful if you wish to store your secret database
credentials directly on the server and not in a version control system. This feature can be easily demonstrated by the
following example:
environments:
default_migration_table: phinxlog
default_database: development
production:
adapter: mysql
host: %%PHINX_DBHOST%%
name: %%PHINX_DBNAME%%
user: %%PHINX_DBUSER%%
pass: %%PHINX_DBPASS%%
port: 3306
charset: utf8
1.6.6 Supported Adapters
Phinx currently supports the following database adapters natively:
• MySQL: specify the mysql adapter.
• PostgreSQL: specify the pgsql adapter.
• SQLite: specify the sqlite adapter.
• SQL Server: specify the sqlsrv adapter.
Declaring an SQLite database uses a simplified structure:
22
Chapter 1. Contents
Phinx Documentation, Release 0.4.2.1
environments:
development:
adapter: sqlite
name: ./data/derby
testing:
adapter: sqlite
memory: true
# Setting memory to *any* value overrides name
When using the sqlsrv adapter and connecting to a named instance of SQLServer you should omit the port setting
as sqlsrv will negotiate the port automatically.
You can provide a custom adapter by registering an implementation of the Phinx\Db\Adapter\AdapterInterface with
AdapterFactory:
$name = ’fizz’;
$class = ’Acme\Adapter\FizzAdapter’;
AdapterFactory::instance()->registerAdapter($name, $class);
Adapters can be registered any time before $app->run() is called, which normally called by bin/phinx.
1.7 Copyright
License
(The MIT license)
Copyright (c) 2012 Rob Morgan
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1.7. Copyright
23
Phinx Documentation, Release 0.4.2.1
24
Chapter 1. Contents
CHAPTER 2
Indices and tables
• genindex
• modindex
• search
25
Phinx Documentation, Release 0.4.2.1
26
Chapter 2. Indices and tables
Index
C
Commands, 18
Configuration, 20
Copyright, 23
G
Goals, 3
I
Installation, 3
Introduction, 3
W
Writing Migrations, 4
27