当前位置: 首页 > news >正文

PHP数据迁移与版本控制工具

PHP数据迁移与版本控制工具

数据库迁移是管理数据库结构变更的标准方式。每次修改都记录在迁移文件中,团队按顺序执行。今天说说PHP中数据迁移的实现。

迁移管理器的实现。

```php
class Migration
{
protected PDO $pdo;

public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}

public function up(): void {}
public function down(): void {}
}

class MigrationRunner
{
private PDO $pdo;
private string $migrationDir;
private string $table = 'migrations';

public function __construct(PDO $pdo, string $migrationDir)
{
$this->pdo = $pdo;
$this->migrationDir = rtrim($migrationDir, '/');
$this->initTable();
}

private function initTable(): void
{
$this->pdo->exec("
CREATE TABLE IF NOT EXISTS {$this->table} (
id INT AUTO_INCREMENT PRIMARY KEY,
migration VARCHAR(255) NOT NULL,
batch INT NOT NULL,
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");
}

public function migrate(): void
{
$executed = $this->getExecuted();
$files = $this->getMigrationFiles();
$batch = $this->getNextBatch();
$pending = array_diff($files, $executed);

if (empty($pending)) {
echo "所有迁移已完成\n";
return;
}

foreach ($pending as $file) {
echo "执行: $file\n";
$migration = $this->loadMigration($file);

try {
$this->pdo->beginTransaction();
$migration->up();
$this->record($file, $batch);
$this->pdo->commit();
echo " 完成\n";
} catch (Exception $e) {
$this->pdo->rollBack();
echo " 失败: {$e->getMessage()}\n";
}
}
}

public function rollback(): void
{
$lastBatch = $this->getLastBatch();
if ($lastBatch === 0) {
echo "没有可回滚的迁移\n";
return;
}

$migrations = $this->getBatchMigrations($lastBatch);
foreach (array_reverse($migrations) as $file) {
echo "回滚: $file\n";
$migration = $this->loadMigration($file);
$migration->down();
$this->remove($file);
}
}

private function getExecuted(): array
{
return $this->pdo->query("SELECT migration FROM {$this->table}")->fetchAll(PDO::FETCH_COLUMN);
}

private function getMigrationFiles(): array
{
$files = glob($this->migrationDir . '/*.php');
sort($files);
return array_map('basename', $files);
}

private function getNextBatch(): int
{
return (int)$this->pdo->query("SELECT COALESCE(MAX(batch), 0) FROM {$this->table}")->fetchColumn() + 1;
}

private function getLastBatch(): int
{
return (int)$this->pdo->query("SELECT COALESCE(MAX(batch), 0) FROM {$this->table}")->fetchColumn();
}

private function getBatchMigrations(int $batch): array
{
$stmt = $this->pdo->prepare("SELECT migration FROM {$this->table} WHERE batch = ? ORDER BY id ASC");
$stmt->execute([$batch]);
return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

private function loadMigration(string $file): Migration
{
require_once $this->migrationDir . '/' . $file;
$className = pathinfo($file, PATHINFO_FILENAME);
$className = $this->formatClassName($className);
return new $className($this->pdo);
}

private function formatClassName(string $name): string
{
preg_match('/^\d{4}_\d{2}_\d{2}_\d{6}_(.+)$/', $name, $matches);
if (isset($matches[1])) {
return implode('', array_map('ucfirst', explode('_', $matches[1])));
}
return $name;
}

private function record(string $file, int $batch): void
{
$this->pdo->prepare("INSERT INTO {$this->table} (migration, batch) VALUES (?, ?)")->execute([$file, $batch]);
}

private function remove(string $file): void
{
$this->pdo->prepare("DELETE FROM {$this->table} WHERE migration = ?")->execute([$file]);
}
}
?>

迁移文件示例。

```php
// 2024_01_01_000001_create_users_table.php
class CreateUsersTable extends Migration
{
public function up(): void
{
$this->pdo->exec("
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
status VARCHAR(20) DEFAULT 'active',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");
}

public function down(): void
{
$this->pdo->exec("DROP TABLE IF EXISTS users");
}
}
?>
```

迁移系统的核心是记录已执行的迁移,确保每个迁移只执行一次。回滚功能可以撤销之前的变更。团队协作时,按顺序执行迁移保持数据库结构一致。

http://www.zskr.cn/news/1479883.html

相关文章:

  • 宣城市2026年上门黄金回收白银回收铂金回收测评,五家全城可上门实体店整理 - 干豆腐啊
  • 2026榆林黄金回收白银回收铂金回收怎么变现?实地探访 5 家本地老牌回收店铺 - 中安检金银铂钻回收
  • PotPlayer百度翻译插件:5分钟实现免费字幕实时翻译的终极指南
  • 技术战略转向:从防御到进攻的研发思维与工具革命
  • 永州黄金回收白银回收铂金回收哪家靠谱?2026 实地测评 5 家高人气实体门店 - 信誉隆金银铂奢回收
  • 开箱即用的全球七大洲边界矢量文件(含WGS84坐标系与ArcGIS/QGIS图层样式)
  • 2026湛江黄金回收白银回收铂金回收怎么变现?实地探访 5 家本地老牌回收店铺 - 中安检金银铂钻回收
  • 音频接口核心解析:Line in与Mic in的电平、阻抗与电路设计差异
  • 2026最新长春黄金回收白银回收铂金回收攻略,实地甄选五家优质实体店 - 诚金汇钻回收公司
  • 上饶市2026年上门黄金回收白银回收铂金回收测评,五家全城可上门实体店整理 - 干豆腐啊
  • 延安黄金回收白银回收铂金回收去哪卖?5 家实地探访靠谱门店汇总 2026 - 中业金奢再生回收中心
  • 宜昌市2026年上门黄金回收白银回收铂金回收测评,五家全城可上门实体店整理 - 干豆腐啊
  • 3步为Windows 11 LTSC系统安装微软商店:终极完整指南
  • 咸阳黄金回收白银回收铂金回收哪家靠谱?2026 实地测评 5 家高人气实体门店 - 信誉隆金银铂奢回收
  • 封号≠权益清零,CSDN AI营销权限保留机制深度解析,附官方未公开的3层申诉权重算法
  • 宜春市2026年上门黄金回收白银回收铂金回收测评,五家全城可上门实体店整理 - 干豆腐啊
  • 2026最新伊春黄金回收白银回收铂金回收攻略,实地甄选五家优质实体店 - 诚金汇钻回收公司
  • 终极OBS多平台直播解决方案:5分钟实现高效同步推流
  • FPGA IO设计实战:Cyclone II引脚配置、高速接口与信号完整性解析
  • 岳阳市2026年上门黄金回收白银回收铂金回收测评,五家全城可上门实体店整理 - 干豆腐啊
  • 从胜利VC8045-II拆解看经典台式万用表的设计哲学与维修要点
  • 工程师如何通过原版英文媒体资源提升技术英语与行业视野
  • 2026咸阳黄金回收白银回收铂金回收怎么变现?实地探访 5 家本地老牌回收店铺 - 中安检金银铂钻回收
  • PCB设计铺铜实战指南:从Protel规则设置到高速电路应用
  • PCIE AC耦合电容设计避坑指南:从原理到实战的完整解析
  • 高速PCB设计实战:Allegro约束管理与信号完整性优化
  • 枣庄黄金回收白银回收铂金回收哪家靠谱?2026 实地测评 5 家高人气实体门店 - 信誉隆金银铂奢回收
  • 2026芜湖黄金回收白银回收铂金回收怎么变现?实地探访 5 家本地老牌回收店铺 - 中安检金银铂钻回收
  • 湘潭黄金回收白银回收铂金回收哪家靠谱?2026 实地测评 5 家高人气实体门店 - 信誉隆金银铂奢回收
  • MTKClient刷机教程:三步完成联发科设备救砖与数据恢复