gruberro / php-mongo-migrations
管理您的 MongoDB 文档的更改
0.5.1
2020-01-28 12:49 UTC
Requires
- php: ^7.0
- mongodb/mongodb: ^1.0.0
- symfony/console: ^3.0|^4.0|^5.0
Requires (Dev)
- phpunit/phpunit: ^5.7.27 || ^6.0 || ^7.0 || ^8.0
README
此命令行应用程序支持您管理 MongoDB 文档的迁移。这些迁移应作为代码更改的一部分,并通过您的部署执行。
安装
composer require gruberro/php-mongo-migrations=^0.2
编写迁移
您可以通过实现 Gruberro\MongoDbMigrations\MigrationInterface
接口来编写自己的迁移
<?php declare(strict_types=1); namespace MyMigrations; use Gruberro\MongoDbMigrations; use MongoDB\Database; class CreateUserCollection implements MongoDbMigrations\MigrationInterface { /** * {@inheritdoc} */ public function getId(): string { return 'create-user-collection-and-its-indexes'; } /** * {@inheritdoc} */ public function getCreateDate(): \DateTime { return new \DateTime('2016-02-25 16:30:00'); } /** * Creates a user collection and it's indexes * * This migration creates the required user collection to establish an application login and it's required indexes. * An overall admin user is created as well. * * {@inheritdoc} */ public function execute(Database $db) { $userCollection = $db->selectCollection('user'); $userCollection->createIndex(['email_address' => 1], ['unique' => true]); $userCollection->insertOne(['username' => 'admin', 'password' => password_hash('topsecret', PASSWORD_DEFAULT), 'email_address' => 'admin@exmaple.com']); } }
您可以选择实现 Gruberro\MongoDbMigrations\RunAlwaysMigrationInterface
接口,以确保在每次运行时都执行迁移类。
实现 Gruberro\MongoDbMigrations\ContextualMigrationInterface
将允许您指定一系列上下文,以对迁移提供更多控制。
查看 示例 以获取更多信息。
使用命令行界面
现在您可以通过启动迁移命令轻松执行迁移
./vendor/bin/migrations php-mongodb-migrations:migrate -c stage1 -c stage2 -s mongodb://:27017 my_database path/to/my/migrations/ path/to/other/migrations
内部处理顺序
- 从配置的目录收集所有迁移
- 检查所有迁移的唯一性(
getId()
) - 根据创建日期(
getCreateDate()
)对所有迁移进行排序 - 通过在
DATABASE_MIGRATIONS_LOCK
中创建特殊文档来锁定其他运行(查看php-mongodb-migrations:release-lock
命令以手动释放锁定) - 如果执行迁移,则
- 至少有一个上下文匹配(没有上下文始终匹配)且
- 迁移尚未执行过或
- 迁移被标记为始终运行。
- 在集合
DATABASE_MIGRATIONS
中存储成功执行的迁移。 - 在任何情况下都释放
DATABASE_MIGRATIONS_LOCK
中的运行锁定。