This tutorial demonstrates using Phinx, a framework-agnostic database migration tool, to manage database schema changes. It emphasizes the advantages of migrations over SQL dumps for team collaboration and version control.
Key Benefits of Using Phinx:
phinx.yml
) generation are straightforward.phinx.yml
.Getting Started:
Installation: Install Phinx using Composer: composer require robmorgan/phinx --dev
Initialization: Generate the configuration file: php vendor/bin/phinx init
(Rename this to my-phinx.yml
to allow for multiple configurations if needed).
Configuration (my-phinx.yml
): Populate the my-phinx.yml
file with your database credentials. Example:
paths: migrations: db/migrations environments: default_migration_table: phinxlog default_database: development development: adapter: mysql host: localhost name: homestead user: homestead pass: 'secret' port: 3306 charset: utf8
Creating Migrations: Generate migration files using: php vendor/bin/phinx create [MigrationName] -c my-phinx.yml
(e.g., php vendor/bin/phinx create Tag
).
Writing Migrations: Populate the migration files (e.g., 20241027100000_Tag.php
) using Phinx's API (not raw SQL) for creating tables and columns. Example:
<?php use Phinx\Migration\AbstractMigration; class Tag extends AbstractMigration { public function change() { $table = $this->table('tag'); $table->addColumn('name', 'string', ['limit' => 45, 'null' => false]) // ... other columns ... ->create(); } }
Running Migrations: Apply migrations using: php vendor/bin/phinx migrate -c my-phinx.yml
Rollback: To undo migrations: php vendor/bin/phinx rollback -c my-phinx.yml
Advanced Techniques:
phinx.yml
.Frequently Asked Questions:
This revised response streamlines the explanation, focusing on key concepts and providing concise code examples. It also incorporates the images provided, maintaining their original format and position.
The above is the detailed content of Phinx - the Migration Library You Never Knew You Needed. For more information, please follow other related articles on the PHP Chinese website!