stratdes / php-mongo-migrations
管理您的 MongoDB 文档的更改
0.4.0
2024-08-18 09:55 UTC
Requires
- php: >=7.0 | <= 8.3
- mongodb/mongodb: ^1.0.0
- symfony/console: ^3.0|^4.0|^5.0|^6.0|^7.0
Requires (Dev)
- phpunit/phpunit: ^5.7.27 || ^6.0 || ^7.0 || ^8.0 || ^9.0
This package is auto-updated.
Last update: 2024-09-18 10:12:09 UTC
README
此命令行应用程序支持您管理 MongoDB 文档的迁移。这些迁移应成为您代码更改的一部分,并且可以通过您的部署执行。
安装
composer require stratdes/php-mongo-migrations=^0.1
编写迁移
您可以通过实现 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
中的运行锁。