CakePHP3のマイグレーションでデータベースを構築する
- 公開:
- 更新:
- カテゴリ: PHP CakePHP
- タグ: PHP,migration,CakePHP,3.5
PHPフレームワークにはマイグレーションという機能があり、データベースの構築をコードで管理していく事が出来ます。こうすることで、チームでコーディングしていた場合にテーブルやカラムの追加・変更が必要になったり、新たなメンバーがアサインされてもコマンド一つでデータベースを構築できて便利です。
このマイグレーションという機能は、CakePHPにももちろん入っています。今回はこの機能を使ってデータベースを構築していきます。
[公式] Migrations
https://book.cakephp.org/3.0/ja/migrations.html
- アジェンダ
開発環境
- Linux CentOS 7
- Apache 2.4
- PHP 7.1
- MySQL 5.7
- CakePHP 3.5
データベースを1つ作成しておいてください。作成するのはスキーマのみで、テーブルは無くてOKです。
マイグレーションの有効化
CakePHP3はデフォルトではマイグレーションが有効になっていません。
bootstrap.php にてコメントアウトされている Plugin::load('Migrations'); のコメントアウトを外すことで、マイグレーションが有効になります。
- config/bootstrap.php
-
/*
* Plugins need to be loaded manually, you can either load them one by one or all of them in a single call
* Uncomment one of the lines below, as you need. make sure you read the documentation on Plugin to use more
* advanced ways of loading plugins
*
* Plugin::loadAll(); // Loads all plugins at once
* Plugin::load('Migrations'); //Loads a single plugin named Migrations
*
*/
Plugin::load('Migrations');
作成するテーブルについて
今回は、ユーザ情報を管理するusersテーブルを作成します。それぞれのカラム構成は以下の通りです。
- id
- 主キー
- name
- ユーザ名
- メールアドレス
- password
- パスワード
- role
- ロール
- last_logined_at
- 最終ログイン日時
- created
- 作成日
- modified
- 更新日
既存データベースの状態からマイグレーションファイルを作成する
マイグレーション用のベースファイルを作成します。既存のデータベース情報を取得し、マイグレーションの初期情報として持っておきます。
cakephpルートディレクトリへ移動し、以下のbakeコマンドを叩きます。
# CakePHPのルートディレクトリへ移動する
cd /path/to/cakephp
# bakeコマンドでマイグレーションの初期ファイルを生成する
bin/cake bake migration_snapshot Initial
# 実行結果
[demo@localhost cakephp]# bin/cake bake migration_snapshot Initial
Creating file /var/www/html/cakephp/config/Migrations/20180120084203_Initial.php
Wrote `/var/www/html/cakephp/config/Migrations/20180120084203_Initial.php`
Marking the migration 20180120084203_Initial as migrated...
using migration paths
- /var/www/html/cakephp/config/Migrations
using seed paths
- /var/www/html/cakephp/config/Seeds
Migration `20180120084203` successfully marked migrated !
Creating a dump of the new database state...
using migration paths
- /var/www/html/cakephp/config/Migrations
using seed paths
- /var/www/html/cakephp/config/Seeds
Writing dump file `/var/www/html/cakephp/config/Migrations/schema-dump-default.lock`...
Dump file `/var/www/html/cakephp/config/Migrations/schema-dump-default.lock` was successfully written
cakephp/config/Migrations 配下に XXXX_Initial.php と schema-dump-default.lock が生成されます。
- cakephp/config/Migrations/XXXX_Initial.php
-
<?php
use Migrations\AbstractMigration;
class Initial extends AbstractMigration
{
public function up()
{
}
public function down()
{
}
}
データベース内は空の状態なので、ファイルの中も何も無い状態です。
今回は空ですが、例えば既に作成済みのデータベース&テーブルを使う場合は、ここにその情報が記録されます。
usersテーブル用のマイグレーションファイルの作成
それではusersテーブルのマイグレーションファイルを作成します。
cakephpルートディレクトリへ移動し、以下のbakeコマンドを叩きます。
# CakePHPのルートディレクトリへ移動する
cd /path/to/cakephp
# bakeコマンドでUsersテーブルのマイグレーションファイルを生成する
bin/cake bake migration CreateUsers name:string email:string:unique:EMAIL_INDEX password:string role:integer[1]:indexType:indexRole last_login_at created modified
# 実行結果
[demo@localhost cakephp]# bin/cake bake migration CreateUsers name:string email:string:unique:EMAIL_INDEX password:string role:integer[1]:indexType:indexRole last_login_at created modified
Creating file /var/www/html/cakephp/config/Migrations/20180120085924_CreateUsers.php
Wrote `/var/www/html/cakephp/config/Migrations/20180120085924_CreateUsers.php`
今回発行したbakeコマンドについて、書式は以下のようになっています。
# bakeコマンドでテーブルのマイグレーションファイルを生成する書式
bin/cake bake migration CreateTablename [カラム名1]:[カラム情報]:[カラム情報] [カラム名2] [カラム名3]:[カラム情報] [カラム名4]
カラム名や型情報、インデックスなどを:(コロン)つなぎで記述し、半角スペース区切りで必要な数のカラムを定義していきます。
尚、主キーとなるidカラムについては記述しなくてもマイグレーション実行時に自動的にテーブルへ挿入されるため、ここでは記述していません。
その他、「created」「modified」そしてサフィックス(接尾辞)が「_at」のカラム名の場合は自動的にdatetime型が挿入されるなど、色々なルールがあります。
bakeコマンドを叩くと、 cakephp/config/Migrations 配下に XXXX_CreateUsers.php が生成されます。
cakephp
├─ config
│ ├─ Migrations
│ │ ├─ 20180120085221_Initial.php
│ │ ├─ 20180120085924_CreateUsers.php
│ │ └─ schema-dump-default.lock
- cakephp/config/Migrations/XXXX_CreateUsers.php
-
<?php
use Migrations\AbstractMigration;
class CreateUsers extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
* @return void
*/
public function change()
{
$table = $this->table('users');
$table->addColumn('name', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addColumn('email', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addColumn('password', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addColumn('role', 'integer', [
'default' => 0,
'limit' => 1,
'null' => false,
]);
$table->addColumn('last_login_at', 'datetime', [
'default' => null,
'null' => false,
]);
$table->addColumn('created', 'datetime', [
'default' => null,
'null' => false,
]);
$table->addColumn('modified', 'datetime', [
'default' => null,
'null' => false,
]);
$table->addIndex([
'email',
], [
'name' => 'EMAIL_INDEX',
'unique' => true,
]);
$table->addIndex([
'role',
], [
'name' => 'indexRole',
'unique' => false,
]);
$table->create();
}
}
マイグレーション実行
それではマイグレーションを実施し、テーブルを構築します。
cakephpルートディレクトリへ移動し、以下のbakeコマンドを叩きます。
# CakePHPのルートディレクトリへ移動する
cd /path/to/cakephp
# bakeコマンドでマイグレーションを実行する
bin/cake migrations migrate
# 実行結果
[demo@localhost cakephp]# bin/cake migrations migrate
using migration paths
- /var/www/html/cakephp/config/Migrations
using seed paths
- /var/www/html/cakephp/config/Seeds
using environment default
using adapter mysql
using database cake_p
== 20180120085924 CreateUsers: migrating
== 20180120085924 CreateUsers: migrated 0.6877s
All Done. Took 0.7433s
using migration paths
- /var/www/html/cakephp/config/Migrations
using seed paths
- /var/www/html/cakephp/config/Seeds
Writing dump file `/var/www/html/cakephp/config/Migrations/schema-dump-default.lock`...
Dump file `/var/www/html/cakephp/config/Migrations/schema-dump-default.lock` was successfully written
実行が完了したらMySQLへログインし確認します。
mysql> show tables;
+------------------+
| Tables_in_cake_p |
+------------------+
| phinxlog |
| users |
+------------------+
mysql> show columns from users;
+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| email | varchar(255) | NO | UNI | NULL | |
| password | varchar(255) | NO | | NULL | |
| role | int(1) | NO | MUL | 0 | |
| last_login_at | datetime | NO | | NULL | |
| created | datetime | NO | | NULL | |
| modified | datetime | NO | | NULL | |
+---------------+--------------+------+-----+---------+----------------+
usersテーブルが作成されました。idカラムについても、自動で挿入されています。
ロールバック実行
ロールバックを行うと、実施されたマイグレーションを遡り、データベース構造を過去の状態に戻すことができます。
cakephpルートディレクトリへ移動し、以下のbakeコマンドを叩きます。
# CakePHPのルートディレクトリへ移動する
cd /path/to/cakephp
# bakeコマンドでロールバックを実行する
bin/cake migrations rollback
# 実行結果
[demo@localhost cakephp]# bin/cake migrations rollback
using migration paths
- /var/www/html/cakephp/config/Migrations
using seed paths
- /var/www/html/cakephp/config/Seeds
using environment default
using adapter mysql
using database cake_p
ordering by creation time
== 20180120085924 CreateUsers: reverting
== 20180120085924 CreateUsers: reverted 0.1363s
All Done. Took 0.1470s
using migration paths
- /var/www/html/cakephp/config/Migrations
using seed paths
- /var/www/html/cakephp/config/Seeds
Writing dump file `/var/www/html/cakephp/config/Migrations/schema-dump-default.lock`...
Dump file `/var/www/html/cakephp/config/Migrations/schema-dump-default.lock` was successfully written
実行が完了したらMySQLへログインし確認します。
mysql> show tables;
+------------------+
| Tables_in_cake_p |
+------------------+
| phinxlog |
+------------------+
ロールバックが実行され、usersテーブルが無くなりました。
マイグレーションのステータス確認
マイグレーションがどこまで実施されていて、どこまでが実施されていないのか、ステータスを確認することができます。
cakephpルートディレクトリへ移動し、以下のbakeコマンドを叩きます。
# CakePHPのルートディレクトリへ移動する
cd /path/to/cakephp
# bakeコマンドでマイグレーションのステータスを確認する
bin/cake migrations status
# 実行結果
[demo@localhost cakephp]# bin/cake migrations status
using migration paths
- /var/www/html/cakephp/config/Migrations
using seed paths
- /var/www/html/cakephp/config/Seeds
using environment default
Status Migration ID Migration Name
-----------------------------------------
up 20180120085221 Initial
up 20180120085924 CreateUsers
全てのマイグレーションが実行済みである事が確認できます。
以上で作業は完了となります。
マイグレーションとロールバックを行えば、何度でもデータベースを構築しなおすことができます。また、本番運用時にも、アップデートでカラム追加や変更等の必要が出た場合にマイグレーションを実施することで容易に対応することが出来るので便利ですので、是非試してみてください。