在非 laravel 專案中使用 laravel 的特性 4: 資料庫遷移 migration

ZouZhipeng發表於2021-02-23

安裝 Eloquent ORM 所需的擴充套件包

composer require illuminate/database

安裝資料庫遷移檔案生成和執行的包

composer require robmorgan/phinx

新建資料庫配置檔案

在專案根目錄建立 config/db.php

<?php

define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PASSWORD', 'secret');
define('DB_PORT', 3306);

完善 composer.json,新增專案的自動載入

{
  "require": {
    "symfony/var-dumper": "^5.2",
    "illuminate/validation": "^8.28",
    "illuminate/database": "^8.28",
    "doctrine/dbal": "^3.0",
    "illuminate/events": "^8.28",
    "robmorgan/phinx": "^0.12.5"
  },
  "autoload": {
    "files": [
      "helpers/laravel_helpers.php"
    ],
    "psr-4": {
      "App\\": "src"
    }
  }
}

更新一下

composer du

擴充套件 Phinx,使其支援 laravel migration

新建 src/Migration/Migration.php 檔案

<?php

namespace App\Migration;

use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Builder;
use Phinx\Migration\AbstractMigration;

class Migration extends AbstractMigration
{
    /** @var Capsule $capsule */
    public $capsule;
    /** @var Builder $capsule */
    public $schema;

    public function init()
    {
        $this->capsule = new Capsule;
        $this->capsule->addConnection([
            'driver' => 'mysql',
            'host' => DB_HOST,
            'port' => DB_PORT,
            'database' => DB_NAME,
            'username' => DB_USER,
            'password' => DB_PASSWORD,
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
        ]);

        $this->capsule->bootEloquent();
        $this->capsule->setAsGlobal();
        $this->schema = $this->capsule->schema();
    }
}

在專案根目錄新建一個 database/migrations 目錄,與 laravel 保持一致

為 Phinx 建立配置檔案 config/phinx.php

<?php

require __DIR__ . '/db.php';

return [
    'paths' => [
        'migrations' => 'database/migrations',
    ],
    'migration_base_class' => '\App\Migration\Migration',
    'environments' => [
        'default_migration_table' => 'migrations',
        'default_database' => 'dev',
        'dev' => [
            'adapter' => 'mysql',
            'host' => DB_HOST,
            'name' => DB_NAME,
            'user' => DB_USER,
            'pass' => DB_PASSWORD,
            'port' => DB_PORT,
        ],
    ],
];

命令列建立資料庫遷移檔案

# php vendor/bin/phinx create MyFirstMigration -c config/phinx.php
Phinx by CakePHP - https://phinx.org.
using config file config/phinx.php
using config parser php
using migration paths
- /path/to/project/root/database/migrations
using migration base class \App\Migration\Migration
using default template
created database/migrations/20210223011109_my_first_migration.php

修改資料庫遷移檔案,增加 up()down() 方法

<?php

use \App\Migration\Migration;

class MyFirstMigration extends Migration
{
    public function up()
    {
        $this->schema->create('widgets', function (Illuminate\Database\Schema\Blueprint $table) {
            // Auto-increment id
            $table->increments('id');
            $table->integer('serial_number');
            $table->string('name');
            // Required for Eloquent's created_at and updated_at columns
            $table->timestamps();
        });
    }

    public function down()
    {
        $this->schema->drop('widgets');
    }
}

命令列執行資料庫遷移

# php vendor/bin/phinx migrate -c config/phinx.php
Phinx by CakePHP - https://phinx.org.
using config file config/phinx.php
using config parser php
using migration paths
- /path/to/project/root/database/migrations
warning no environment specified, defaulting to: dev
using adapter mysql
using database test
ordering by creation time
== 20210223011109 MyFirstMigration: migrating
== 20210223011109 MyFirstMigration: migrated 0.0640s
All Done. Took 0.2421s

此時,檢視資料庫,可以看到 test.widgets 表已自動生成。遷移記錄在 test.migrations 表中

新建模型檔案 src/Eloquent/Widget.php

<?php

namespace App\Eloquent;

use Illuminate\Database\Eloquent\Model;

class Widget extends Model
{
}

專案根目錄新建入口 index/migration.php

<?php

require_once __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../config/db.php';

use App\Eloquent\Widget;
use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;
$capsule->addConnection([
    'driver' => 'mysql',
    'host' => DB_HOST,
    'port' => DB_PORT,
    'database' => DB_NAME,
    'username' => DB_USER,
    'password' => DB_PASSWORD,
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
]);
$capsule->bootEloquent();
$capsule->setAsGlobal();

$widget = new Widget();
$widget->serial_number = 123;
$widget->name = 'My Test Widget';
$widget->save();

$widgets = Widget::all();
foreach ($widgets as $widget) {
    echo "<h1>$widget->name</h1>";
    echo "<p>Serial number: $widget->serial_number</p>";
}

命令列開啟服務 php -S localhost:8000 並訪問 http://localhost:8000/index/migration.php 即可。

可用遷移命令,沒有 laravel 多,但也夠用

# php vendor/bin/phinx list
Phinx by CakePHP - https://phinx.org.

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display help for the given command. When no command is given display help for the list command
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  breakpoint    Manage breakpoints
  create        Create a new migration
  help          Displays help for a command
  init          Initialize the application for Phinx
  list          Lists commands
  migrate       Migrate the database
  rollback      Rollback the last or to a specific migration
  status        Show migration status
  test          Verify the configuration file
 list
  list:aliases  List template class aliases
 seed
  seed:create   Create a new database seeder
  seed:run      Run database seeders

專案目錄結構

# tree -I vendor
.
├── composer.json
├── composer.lock
├── config
│   ├── db.php
│   └── phinx.php
├── database
│   └── migrations
│       └── 20210223044643_my_first_migration.php
├── helpers
│   └── laravel_helpers.php
├── index
│   ├── dd.php
│   ├── migration.php
│   ├── orm.php
│   └── validator.php
├── lang
│   └── zh_cn
│       └── validation.php
├── orm.php
└── src
    ├── Eloquent
    │   ├── User.php
    │   └── Widget.php
    ├── Handlers
    │   └── Validator.php
    └── Migration
        └── Migration.php

參考 致謝

  1. How to use Eloquent ORM migrations outside Laravel
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章