wpdesk/wp-migrations
Composer 安装命令:
composer require wpdesk/wp-migrations
包简介
Doctrine Migrations clone suited for WordPress purposes.
README 文档
README
WP Migrations is a simple database migration library for WordPress projects, inspired by Doctrine Migrations. It allows developers to manage database schema updates incrementally using versioned PHP classes, ensuring that schema changes are applied safely, in order, and without race conditions in concurrent environments.
Unlike traditional migration systems, WP Migrations is tailored specifically for the WordPress runtime environment. It utilizes WordPress features such as the \wpdb database connection, options table storage for schema versions, post-based mutex locking, and WordPress admin notice UI for logging errors.
Key Features
- WordPress Integration: Built natively to interact with
\wpdband use the WordPress database abstraction layer (including automatic availability ofdbDelta()). - Multiple Repository Drivers: Supports loading migration classes directly from static lists via ArrayMigrationsRepository or dynamically from folders via FilesystemMigrationsRepository.
- Concurrency Protection: Leverages a robust locking mechanism using a mutex implementation (such as
WordpressPostMutex) to prevent concurrent migration executions that could corrupt database schemas. - Fail-safe Logic and Verification: Includes an
is_needed()check inside migrations, allowing double-verification of DB state (e.g., column existence checks) before attempting modifications. - Admin Notice Notifications: Persists migration failures and displays native WordPress admin notices using MigrationErrorNotice to warn administrators of database update issues.
- Robust Database Logging: Built-in WpdbLogger that logs migration lifecycle stages directly to a dedicated database option, keeping the last 30 log records.
Requirements
The library requires the following system dependencies, as defined in composer.json:
- PHP:
^7.4or^8 - JSON Extension: Ext-JSON enabled (
*) - PSR Log:
psr/logversion^1 - WP Desk Mutex:
wpdesk/wp-mutexversion^1.1(used for transaction-like locking) - WP Desk Notice:
wpdesk/wp-noticeversion^3.3(used for admin-facing error notices) - WordPress: A standard WordPress environment (providing
\wpdb, database options APIs, and admin functions)
Installation
Install the package via Composer:
composer require wpdesk/wp-migrations
Ensure that your project includes the Composer autoloader:
require_once __DIR__ . '/vendor/autoload.php';
Usage
Creating a Migration Class
To define a database migration, you must create a class that extends AbstractMigration.
Your migration class should implement the up() method and, optionally, override the is_needed() method. File names and class names must start with the Version prefix (e.g., Version_20260619_CreateTable.php).
<?php
declare(strict_types=1);
namespace MyPlugin\Migrations;
use WPDesk\Migrations\AbstractMigration;
class Version_20260619_CreateTable extends AbstractMigration {
/**
* Verify if this migration still needs to run.
* Even if the migration version is not recorded in the DB, this check acts
* as a fallback to prevent errornous table creation if it already exists.
*/
public function is_needed(): bool {
$table_name = $this->wpdb->prefix . 'my_custom_table';
return $this->wpdb->get_var( "SHOW TABLES LIKE '{$table_name}'" ) !== $table_name;
}
/**
* Run the migration schema change.
*
* @return bool True if successful, false on failure.
*/
public function up(): bool {
$table_name = $this->wpdb->prefix . 'my_custom_table';
$charset_collate = $this->wpdb->get_charset_collate();
$sql = "CREATE TABLE {$table_name} (
id bigint(20) NOT NULL AUTO_INCREMENT,
title varchar(255) NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
PRIMARY KEY (id)
) {$charset_collate};";
// WpdbMigrator automatically requires 'wp-admin/includes/upgrade.php',
// so dbDelta is globally available.
dbDelta( $sql );
return empty( $this->wpdb->last_error );
}
}
Running Migrations
To run migrations, instantiate WpdbMigrator and call the migrate() method. There are two primary factory methods to initialize the migrator:
1. From a List of Classes
If you have a defined, static list of migration classes, use the static from_classes() factory method:
use WPDesk\Migrations\WpdbMigrator;
use MyPlugin\Migrations\Version_20260619_CreateTable;
use MyPlugin\Migrations\Version_20260620_AddColumn;
$migrator = WpdbMigrator::from_classes(
[
Version_20260619_CreateTable::class,
Version_20260620_AddColumn::class,
],
'my_plugin_db_schema_version' // Unique option name in wp_options
);
$migrator->migrate();
2. From Directories (Dynamic Class Discovery)
If you store all your migrations in one or more directories, use the static from_directories() factory method:
use WPDesk\Migrations\WpdbMigrator;
$migrator = WpdbMigrator::from_directories(
[
__DIR__ . '/src/Migrations',
],
'my_plugin_db_schema_version' // Unique option name in wp_options
);
$migrator->migrate();
[!NOTE] When using
from_directories(), migration file names must start with theVersionprefix (e.g.,Version_20260619_CreateTable.php). Files not matching this prefix will be skipped.
Advanced Configuration
If you require custom dependencies (e.g., custom mutex logic, a custom logging service, or a different comparator), you can instantiate WpdbMigrator directly using its constructor:
use WPDesk\Migrations\WpdbMigrator;
use WPDesk\Migrations\ArrayMigrationsRepository;
use WPDesk\Migrations\Version\WpdbMigrationFactory;
use WPDesk\Migrations\Version\AlphabeticalComparator;
use WPDesk\Migrations\WpdbLogger;
global $wpdb;
$logger = new WpdbLogger( 'custom_migration_log' );
$repository = new ArrayMigrationsRepository(
[
Version_20260619_CreateTable::class,
],
new WpdbMigrationFactory( $wpdb, $logger ),
new AlphabeticalComparator()
);
$migrator = new WpdbMigrator(
$wpdb,
'custom_db_option',
$repository,
new AlphabeticalComparator(),
$logger,
null, // Custom Mutex (omitting defaults to WordpressPostMutex)
null // Custom MigrationErrorNotice (omitting defaults to MigrationErrorNotice)
);
$migrator->migrate();
Backward Compatibility / Legacy APIs
- Removed
AbstractMigration::down(): As of version1.1.0, thedown()method has been completely removed from AbstractMigration. In standard WordPress environments, rolling back schema changes automatically or reliably is highly impractical and rarely used. - Migration Schema Checking via
is_needed(): Instead of relying solely on version options to skip/run migrations, migration classes should implementis_needed(). This allows a migration to inspect the actual database schema/state before executing queries inup(), ensuring backward compatibility and preventing failures if a version option gets out of sync with the physical database structure.
Running Tests
The library contains a full test suite including PHPUnit unit tests, PHPStan static analysis, and PHP CodeSniffer style checks. These can be executed using the Composer scripts defined in composer.json.
First, ensure all development dependencies are installed:
composer install
Run All Verification Tools
composer test
Run phpunit Tests Separately
composer test:phpunit
Run phpstan Static Analysis
composer test:phpstan
Run phpcs Code Quality Check
composer test:phpcs
Run phpcs Autofix (GrumPHP)
composer style:fix
License
This library is licensed under the MIT License. For details, please see the LICENSE.md file.
统计信息
- 总下载量: 2.99k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2022-05-13