Data Migration through Migrate API
Migrate API is the most versatile module available for moving arbitrary data between Drupal sites of the same, or even different core version. It provides a unified way of handling any data type, and a simple to implement interface for making more elements available for migration. This tutorial will show you how to create your own migration handler.

When upgrading, importing or simply migrating a Drupal installation to another location, it is convenient if all the different data types are handled in the same area - otherwise, building a clean, easy to understand workflow becomes difficult. Migrate not only centralizes the process to a single interface, but also is internally capable of providing the workflow itself. But how does it work on the backend?

Migration Structure
The word migration implies that the module moves complete sites. This is not entirely true, as migration is prepared to handle alternative sources of data, such as CSV, JSON or XML files, or even PHP arrays. Unified, this is called a Migrate Source. Generally, unless you require something very exotic, the source handlers already provided with the Migrate module should suffice for any arbitrary migration, and I won't be covering it for this tutorial. The API also needs to know where to put the data. This is a Migrate Destination. A destination handler is aware of the fields that can, or need to be filled for a single piece of data, and it is capable of verifying its consistency and saving it as it was intended to be used. Each destination handler lives in its own class, implementing and overriding the necessary methods of the base class MigrateDestination. The Migrate module provides destination handlers for most core data, and the Commerce Migrate module extends this with the Commerce entities, however, it is not unusual that this is insufficient. Here's an example destination handler. Note that all example code below builds on the Migrate 2.6 API, which, at the time of writing this blog entry, is still in development.
-
/**
-
* Our example migration destination handler class.
-
*/
-
class MigrateDestinationExampleData extends MigrateDestination {
-
/**
-
* Returns the key schema.
-
*
-
* This function is intended to return the Schema API definition for the
-
* primary key of the example data type. Note that a primary key is not
-
* necessarily a single field - for example, a Drupal 7 field instance is
-
* identified by field_name, entity_type and bundle, and thus has three
-
* fields in its primary key.
-
*
-
* @return array
-
* An associative array, where the keys are field names, and the values
-
* are valid Schema API definitions for the field.
-
*/
-
public static function getKeySchema() {
-
return array(
-
'example_machine_name' => array(
-
'type' => 'varchar',
-
'length' => 32,
-
'not null' => TRUE,
-
'description' => 'The machine-readable name for this example.',
-
),
-
);
-
}
-
-
/**
-
* Provides a list of available fields on this destination.
-
*
-
* @return array
-
* An associative array, where the keys are field machine names, and the
-
* values are localized field labels.
-
*/
-
public function fields() {
-
return array(
-
'example_machine_name' => t('Machine name'),
-
'example_value' => t('Value'),
-
);
-
}
-
-
/**
-
* Prepares an item for migration.
-
*
-
* At this point, $imported already contains the data defined by the field
-
* mappings. However, all the data is raw - some of it may need to be
-
* reprocessed to a different form.
-
*
-
* It is advised to keep your imported data in an object form, as that makes
-
* manipulating the data in the prepare function possible.
-
*
-
* @param mixed $imported
-
* The data being imported, pre-populated according to field mappings.
-
* @param stdClass $source_row
-
* The row of data provided by the source handler.
-
*/
-
public function prepare($imported, stdClass $source_row) {
-
// Make sure there is an example value, in case it disappeared.
-
if (empty($imported->example_value)) {
-
$imported->example_value = 42;
-
}
-
}
-
-
/**
-
* Imports an item.
-
*
-
* This function handles the validation and saving of data. Any final stages
-
* of processing are also handled here. You are responsible for making sure
-
* your data is valid, and that it is saved.
-
*
-
* @param mixed $imported
-
* The data being imported, already prepared through the prepare methods.
-
* @param stdClass $row
-
* The row of data provided by the source handler.
-
*
-
* @return array|FALSE
-
* On success, an array whose values are the field values for each primary
-
* key field in the newly imported data.
-
* On failure, the function returns FALSE.
-
*/
-
public function import($imported, stdClass $row) {
-
// Save the example data into the database.
-
$success = example_data_save($imported);
-
-
if ($success) {
-
// If the saving was successful, return the primary key, so that the API
-
// knows where an old data was moved.
-
return array($imported->example_machine_name);
-
}
-
else {
-
// If the saving failed, return FALSE - Migrate will indicate this as
-
// an error after the batch process is complete.
-
return FALSE;
-
}
-
}
-
-
/**
-
* Take any additional action after an item has finished importing.
-
*
-
* @param mixed $imported
-
* Object to build. This is the complete object after saving.
-
* @param stdClass $source_row
-
* The row of data provided by the source handler.
-
*/
-
public function complete($imported, stdClass $source_row) {
-
// Retrieve the current migration handler object. This represents the
-
// migration that is currently in progress.
-
$migration = Migration::currentMigration();
-
-
// Set a message on the migration to let the world know that the import
-
// succeeded.
-
$migration->saveMessage('I have imported an item.', Migration::MESSAGE_INFORMATIONAL);
-
}
-
-
/**
-
* Roll back an imported item.
-
*
-
* This function is expected to return the system into the state it was in
-
* before this specific item was imported, assuming the rollbacks happen in
-
* the reverse order as the imports. In any case, the item identified by the
-
* IDs should be deleted or hidden.
-
*
-
* @param $ids
-
* Array of fields representing the key.
-
* This array doesn't work like you'd expect it does - the keys are actually
-
* in the form of 'destid[0-9]+', where the number represents that this is
-
* the nth primary key field defined in the key schema, indexed from 1.
-
*
-
* @return
-
* TRUE on success, FALSE on failure.
-
*/
-
public function rollback(array $ids) {
-
// Retrieve the new machine name of the item being rolled back.
-
$machine_name = $ids['destid1'];
-
-
// Delete this item.
-
example_data_delete($machine_name);
-
-
// Assume that the deletion succeeded and return TRUE.
-
return TRUE;
-
}
-
}
A migration also requires a handler which serves as a bridge between the source and the destination. This bridge is responsible for providing the available source fields, and the default mapping of fields from source to destination. Migrate provides an interface for the user to configure any further mapping, and the moving of the mapped data is done automatically and internally - as such, the only task for you, the developer, is to make sure the data is sane in the destination handler, and to make sure all fields (which make sense) are available for migration in the migrate handler. An example migrate handler is below.
-
/**
-
* The migration handler for the Example Data migration.
-
*/
-
class ExampleDataMigrateExampleMigration extends Migration {
-
public function __construct(array $arguments) {
-
parent::__construct($arguments);
-
-
// A localized description of the data type, which will be displayed on
-
// the migration page.
-
$this->description = t('Migrate Example Data between Drupal sites.');
-
-
// An array of dependencies, for hierarchical migrations. Each array value
-
// must be the machine name for a specific migration (which is not
-
// necessarily the same as the class name).
-
$this->dependencies = array();
-
-
// Define the source key schema in a similar manner to the destination key
-
// schema. This ensures Migrate API can make a distinction between two
-
// data items.
-
$source_key = array(
-
'example_machine_name' => array(
-
'type' => 'varchar',
-
'length' => 32,
-
'not null' => TRUE,
-
'description' => 'The machine-readable name for this example.',
-
),
-
);
-
-
-
// The Map object contains all relevant identifiers - the machine name for
-
// the migration in question, the primary key for the source data and the
-
// primary key for the destination data, the latter two in Schema API
-
// format.
-
$this->map = new MigrateSQLMap($this->machineName,
-
$source_key,
-
MigrateDestinationExampleData::getKeySchema()
-
);
-
-
// In this example, we will be migrating from a database in the
-
// settings.php with the key saved on an example configuration page.
-
$key = variable_get('example_migration_key', 'example');
-
$connection = Database::getConnection('default', $key);
-
-
// Define the query which will be used by Migrate to retrieve all rows
-
// from the database.
-
$query = $connection->select('example_data', 'ed')
-
->fields('ed');
-
-
// Define the source and destination for this migration. Both should be an
-
// object of a class which extends the respective base handler.
-
$this->source = new MigrateSourceSQL($query, array(), NULL, array('map_joinable' => FALSE));
-
$this->destination = new MigrateDestinationExampleData();
-
-
// Create the default field mappings. The user can change this at will on
-
// the migration page.
-
$this->addFieldMapping('example_machine_name', 'example_machine_name');
-
$this->addFieldMapping('example_value', 'example_value')
-
->defaultValue(42);
-
}
-
}
And that's it! Your code now should be able to migrate any amount of Example Data from one Drupal site to another. However, it's not appearing on the interface!
Registering and hierarchy
Before you are able to initiate a migration, you must register it with Drupal. Registration of migrations allows for all configuration to be completed before the user initiates the process. Prior to Migrate 2.6, migrations whose dependencies were met were automatically registered, however, due to popular demand, this is no longer the case. In Migrate 2.6, migrations are also drafted into groups to ease categorization. Adding groups is strongly recommended. To create a group and register a new migration, you must add the following code snippet (to, for example, your configuration form's submit callback):
-
// When registering a migrate group, three parameters are expected:
-
// A machine name for the group being registered, a human readable name
-
// which will be displayed on the migration overview page and an array of
-
// arguments, which apply to all migrations in the migration group.
-
MigrateGroup::register('Example', 'Very Important Migration Of Example Data', array());
-
-
// Registering a migration expects a class name (which is our migration
-
// handler), a machine name, and similarly, arguments.
-
// It should be noted that unless group_name is added to the arguments,
-
// the migration will be added to the 'default' group.
-
Migration::registerMigration('ExampleDataMigrateExampleMigration', 'ExampleData', array('description' => 'Migrate all example datas.', 'group_name' => 'Example'));
Registration of migrations can also be used to your advantage if building hierarchical import of unknown data. For example, let's assume that our example data values in fact define example sub-data. In this case, another migration destination and handler should be defined for the sub-data. But what if the import only makes sense after example data has been imported into the database? Migration handlers can be parametrized in the same way anything else can - any data passed to the arguments array of the register function will also be passed to the constructor of a migration handler. So, for each of the example data instances which were imported, an example sub-data migration can be defined, using the same handler with different parameters. An example code snippet on how to register such migrations follows. Note that the function in question is the complete method of our destination handler; as the complete method will run each time an item is imported, it is guaranteed to register the appropriate migration for every item.
-
public function complete($imported, stdClass $row) {
-
// Retrieve the value of the example data that was imported.
-
$value = $imported['example_value'];
-
// Define the machine name for the new migration.
-
$machine_name = 'ExampleSubData' . $value;
-
// Register the migration.
-
$class = 'ExampleSubDataMigrationClassName';
-
$args = array('value' => $value, 'group_name' => 'Example');
-
Migration::registerMigration($class, $machine_name, $args);
-
}
That concludes this short tutorial on writing your own handlers for the Migrate API. It is an easy-to-use framework, available for a lot more purposes than it is given credit for. Hopefully, the upgrade path for Drupal 8 will use this module for a larger percentage of the data than the upgrade path for Drupal 7 did, as it would certainly allow upgrade jobs to be more streamlined and cleaner.
Related posts

Migrations are becoming a crucial part of Drupal 8, especially in connection with the upcoming Drupal 6 EOL. In this first article, we are going to show you how to quickly migrate your site to Drupal 8.