LoginSignup
3
1

More than 5 years have passed since last update.

phpmigで生成されるMigrationクラスを拡張する

Posted at

はじめに

そもそも、なぜphpmigを使うのか?

いくつかの理由があります。

  • フレームワークのmigrationツールが存在しない、もしくは貧弱
  • doctrineを使ってない

どうせ使うなら、使い勝手を良くしたい

マイグレーションツールとはいえ、実装があるので、コードはなるべく短くしたい。
Migrationクラスを独自の抽象クラスに差し替えることができれば、色々便利な関数作ってコードを短くできそう。

独自の抽象クラスを作成

下記のように、Phpmig\Migration\Migrationクラスを継承した抽象クラスを作ります。

// extension/AbstractMigration.php

use Phpmig\Migration\Migration;

abstract class AbstractMigration extends Migration
{
}

作ったクラスはbootstrapファイルにて、requireする

// phpmig.php
require __DIR__. '/extension/AbstractMigration.php';

カスタムテンプレートの作成

下記のようにカスタムテンプレートを作成。
extends AbstractMigrationにより、既定クラスを独自のものに差し替える。

// template/migration_class.php

<?= "<?php ". PHP_EOL; ?>


class <?= $className ?> extends AbstractMigration
{
    /**
     * Do the migration
     */
    public function up()
    {
    }

    /**
     * Undo the migration
     */
    public function down()
    {
    }
}

カスタムテンプレートの適用

bootstrapファイルにて、$container['phpmig.migrations_template_path']にテンプレートファイルのパスをセットします。

// phpmig.php
$container['phpmig.migrations_template_path'] = __DIR__. '/template/migration_class.php';

generate

generateコマンドにて、ファイルを生成すると、下記のようになります。

$ phpmig generate example
+f ./migrations/20170113094237_example.php
<?php 


class Example extends AbstractMigration
{
    /**
     * Do the migration
     */
    public function up()
    {
    }

    /**
     * Undo the migration
     */
    public function down()
    {
    }
}

おわりに

phpmigは、それほど活発に開発が行われているオープンソースソフトウェアではありません。
物足りないところは、Pull Request出して自分たちで使いやすくしていきましょう。

先日、立て続けに2つPull Request出して、mergeしてもらいました。
気になる方は、こちらを参照ください。

ではでは。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1