PHP Database Migrations

  • webtech

When a software project is in the development phase or during maintenance, sometimes is required to make changes in schema of the database such as add a new table, or column etc. We need to keep track to all these changes, to do this we use the technique of database migration which is a versioning of the database schema similar to source code. This is very useful because if you are part of a team, the other members can take quickly the changes without reloading data, or if a project is in production you can easily rollback if something goes wrong. Many php framework such as yii2, cakephp, symfony have command line tools, you can create and apply migrations.

Let's see an example in yii2, if we have a table with name product and we want to add an extra field, we will have to choose the command migrate/create and give a descriptive name to this migration

yii migrate/create add_field_market_in_products

this will create an file under folder named migrations, it will assign to file with random prefix and in the end the name of the migration add_field_market_in_products, in this file there two functions one with name up and one with name down

use yii\db\Schema;
use yii\db\Migration;

class m150608_200458_add_field_market_in_products extends Migration
    public function up()
    	$this->addColumn('product', 'marketOpportinities, 'TEXT AFTER productDescription');

    public function down()
        echo "m150608_200458_add_field_market_in_products cannot be reverted.\n";
        return false;

then in command line will have press

yii migrate

History of migrations are stored in the database in table with name migration, it includes two columns the first is the name of migration, the other column has name apply_time and stores the time that the migration applied in unixtimestamp format.

php developer

SaaS software, easy to use platform and interface to setup quickly your eshop .