Migration that requires user confirmation to continue

Since there’s a pure Linux underlying PHP, you can use STDIN (actually: php://stdin) and read it with fopen when your PHP script is run in console to stop execution of your script and read a button user pressed.

Since Yii migrations are run in console, you can use this mechanism to ask user whether she or he want to continue with your database migration.

Quite handy in some scenarios (like: destroying entire database), don’t you think?

Here you have a raw example of what I am talking about:

public function down()
{
    /**
     * Confirmation.
     */
    echo "n***************************************n";
    echo "*              WARNING!               *n";
    echo "*                                     *n";
    echo "*    This is an initial migration.    *n";
    echo "* Reverting it will ERASE all tables! *n";
    echo "*                                     *n";
    echo "***************************************nn";
    echo "Continue [Y/N]? ";

    $handle = fopen("php://stdin","r");
    $line = fgets($handle);
    if(strtoupper(trim($line)) !== 'Y') return false;

    /**
     * Drop foreign keys.
     */
    $this->dropForeignKey('fk_contents_users', 'contents');
    $this->dropForeignKey('fk_contents_files', 'contents');
    $this->dropForeignKey('fk_files_users', 'files');
    $this->dropForeignKey('fk_menus_items', 'menus_items');
    $this->dropForeignKey('fk_menus_items_tree', 'menus_items');

    /**
     * Drop tables.
     */
    $this->dropTable('contents');
    $this->dropTable('files');
    $this->dropTable('lookup');
    $this->dropTable('menus');
    $this->dropTable('menus_items');
    $this->dropTable('users');
}

This particular migration will display some nice message to the user executing it and will follow with the execution if and only if the user presses Y on their keyboard. Amen!

Leave a Reply