定制 wpdesk/wp-migrations 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

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 \wpdb and use the WordPress database abstraction layer (including automatic availability of dbDelta()).
  • 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.4 or ^8
  • JSON Extension: Ext-JSON enabled (*)
  • PSR Log: psr/log version ^1
  • WP Desk Mutex: wpdesk/wp-mutex version ^1.1 (used for transaction-like locking)
  • WP Desk Notice: wpdesk/wp-notice version ^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 the Version prefix (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 version 1.1.0, the down() 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 implement is_needed(). This allows a migration to inspect the actual database schema/state before executing queries in up(), 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.

wpdesk/wp-migrations 适用场景与选型建议

wpdesk/wp-migrations 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.04k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 05 月 13 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 wpdesk/wp-migrations 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 wpdesk/wp-migrations 我们能提供哪些服务?
定制开发 / 二次开发

基于 wpdesk/wp-migrations 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 3.04k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 4
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-05-13