aureka/migrate-bundle

提供构建迁移的初始脚手架

dev-master 2014-06-19 16:26 UTC

This package is not auto-updated.

Last update: 2024-09-14 15:46:31 UTC


README

Build Status

为迁移提供少量脚手架。

配置

1. 将此包添加到您的 composer.json 文件中,并执行 composer update

{
    "require": {
        "aureka/migrate-bundle": "*"
    }
}

2. 修改您的 AppKernel.php

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...
            new Aureka\MigrateBundle\AurekaMigrateBundle(),
            );
        // ...
    }
}

3. 在 config.yml 中配置您的旧版数据库

aureka_migrate: database: connector: 'mysqli' host: 'localhost' user: 'root' password: '123' database: 'my_database'

添加迁移器

是时候添加您自己的自定义迁移器了。将每个迁移器声明为带有 aureka_migrate.migrator 标签的服务。

services:
    your_migration_bundle.users_migrator:
            class: Your\MigrationBundle\Migrator\UsersMigrator
            arguments: ['@aureka_migrate.legacy_connection', '@doctrine.orm.entity_manager']
            tags:
                - { name: aureka_migrate.migrator }

迁移器可能如下所示

use Doctrine\Common\Persistence\ObjectManager;

use Aureka\MigrateBundle\Migrator\Migrator,
    Aureka\MigrateBundle\Service\Database\Connection;

class UsersMigrator implements Migrator
{
    private $legacyConnection;
    private $om;

    public function __construct(Connection $legacyConnection, ObjectManager $om)
    {
        $this->legacyConnection = $legacyConnection;
        $this->om = $om;
    }

    public function prepare()
    {
        // Do whatever you need to prepare the migration, like cleaning the destination tables
        return $this;
    }

    public function migrate()
    {
        $users = $this->legacyConnection->fetchAll('SELECT * FROM users');
        foreach ($users as $legacy_user) {
            $user = new User;
            $user->name = $legacy_user['username'];
            // ...
            $this->om->persist($user);
        }
        $this->om->flush();
        return $this;
    }

运行迁移

现在您可以执行以下命令

php app/console aureka_migrate:migrate