在非 laravel 项目中使用 laravel 的特性 4: 数据库迁移 migration

laravel migration

安装 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 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!