MigrateController

Type
Class
Namespace
craft\console\controllers
Inherits
craft\console\controllers\MigrateController » yii\console\controllers\BaseMigrateController (opens new window) » yii\console\Controller (opens new window) » yii\base\Controller (opens new window) » yii\base\Component (opens new window) » yii\base\BaseObject (opens new window)
Implements
yii\base\Configurable (opens new window), yii\base\ViewContextInterface (opens new window)
Uses traits
craft\console\ControllerTrait
Since
3.0.0

Manages Craft and plugin migrations.

A migration means a set of persistent changes to the application environment that is shared among different developers. For example, in an application backed by a database, a migration may refer to a set of changes to the database, such as creating a new table, adding a new table column. This controller provides support for tracking the migration history, updating migrations, and creating new migration skeleton files. The migration history is stored in a database table named migrations. The table will be automatically created the first time this controller is executed, if it does not exist. Below are some common usages of this command:

# creates a new migration named 'create_user_table' for a plugin with the handle pluginHandle.
craft migrate/create create_user_table --plugin=pluginHandle
# applies ALL new migrations for a plugin with the handle pluginHandle
craft migrate up --plugin=pluginHandle

View source (opens new window)

# Public Properties

Property Description
action (opens new window) yii\base\Action (opens new window) – The action that is currently being executed.
behaviors (opens new window) yii\base\Behavior (opens new window) – List of behaviors attached to this component
color (opens new window) boolean (opens new window) – Whether to enable ANSI color in the output.
compact (opens new window) boolean (opens new window) – Indicates whether the console output should be compacted.
defaultAction (opens new window) string (opens new window) – The ID of the action that is used when the action ID is not specified in the request.
help (opens new window) boolean (opens new window) – Whether to display help information about current command.
helpSummary (opens new window) string (opens new window)
id (opens new window) string (opens new window) – The ID of this controller.
interactive (opens new window) boolean (opens new window) – Whether to run the command interactively.
layout (opens new window) null (opens new window), string (opens new window), false (opens new window) – The name of the layout to be applied to this controller's views.
migrationNamespaces (opens new window) array (opens new window) – List of namespaces containing the migration classes.
migrationPath (opens new window) string (opens new window), array (opens new window) – The directory containing the migration classes.
migrator craft\db\MigrationManager
module (opens new window) yii\base\Module (opens new window) – The module that this controller belongs to.
modules (opens new window) yii\base\Module (opens new window) – All ancestor modules that this controller is located within.
noBackup boolean (opens new window) – Skip backing up the database.
noContent boolean (opens new window) – Exclude pending content migrations.
passedOptionValues (opens new window) array (opens new window) – The properties corresponding to the passed options
passedOptions (opens new window) array (opens new window) – The names of the options passed during execution
plugin string (opens new window), craft\base\PluginInterface, null (opens new window) – The handle of the plugin to use during migration operations, or the plugin itself
request (opens new window) yii\base\Request (opens new window), array (opens new window), string (opens new window) – The request.
response (opens new window) yii\base\Response (opens new window), array (opens new window), string (opens new window) – The response.
route (opens new window) string (opens new window) – The route (module ID, controller ID and action ID) of the current request.
silentExitOnException (opens new window) boolean (opens new window) – If true - script finish with ExitCode::OK in case of exception.
templateFile (opens new window) string (opens new window) – The template file for generating new migrations.
track string (opens new window) – The migration track to work with (e.g. craft, content, plugin:commerce, etc.
type string (opens new window), null (opens new window) – The type of migrations we're dealing with here.
uniqueId (opens new window) string (opens new window) – The controller ID that is prefixed with the module ID (if any).
view (opens new window) yii\base\View (opens new window), yii\web\View (opens new window) – The view object that can be used to render views or view files.
viewPath (opens new window) string (opens new window) – The directory containing the view files for this controller.

# migrator

Type
craft\db\MigrationManager
Default value
null
Access
Read-only

View source (opens new window)

# noBackup

Type
boolean (opens new window)
Default value
false
Since
3.4.3

Skip backing up the database.

View source (opens new window)

# noContent

Type
boolean (opens new window)
Default value
false

Exclude pending content migrations.

View source (opens new window)

# plugin

Type
string (opens new window), craft\base\PluginInterface, null (opens new window)
Default value
null

The handle of the plugin to use during migration operations, or the plugin itself

View source (opens new window)

# track

Type
string (opens new window)
Default value
\craft\db\MigrationManager::TRACK_CONTENT
Since
3.5.0

The migration track to work with (e.g. craft, content, plugin:commerce, etc.)

If --plugin is passed, this will automatically be set to the plugin’s track. Otherwise defaults to 'content'.

View source (opens new window)

# type

DEPRECATED

Deprecated in 3.5.0. Use track instead.

Type
string (opens new window), null (opens new window)
Default value
null

The type of migrations we're dealing with here. Can be 'app', 'plugin', or 'content'.

View source (opens new window)

# Public Methods

Method Description
__call() (opens new window) Calls the named method which is not a class method.
__clone() (opens new window) This method is called after the object is created by cloning an existing one.
__construct() (opens new window) Constructor.
__get() (opens new window) Returns the value of an object property.
__isset() (opens new window) Checks if a property is set, i.e. defined and not null.
__set() (opens new window) Sets value of an object property.
__unset() (opens new window) Sets an object property to null.
actionAll() Runs all pending Craft, plugin, and content migrations.
actionCreate() Creates a new migration.
actionDown() (opens new window) Downgrades the application by reverting old migrations.
actionFresh() (opens new window) Drops all tables and related constraints. Starts the migration from the beginning.
actionHistory() (opens new window) Displays the migration history.
actionMark() (opens new window) Modifies the migration history to the specified version.
actionNew() (opens new window) Displays the un-applied new migrations.
actionRedo() (opens new window) Redoes the last few migrations.
actionTo() (opens new window) Upgrades or downgrades till the specified version.
actionUp() Upgrades the application by applying new migrations.
actions() (opens new window) Declares external actions for the controller.
afterAction() (opens new window) This method is invoked right after an action is executed.
ansiFormat() (opens new window) Formats a string with ANSI codes.
attachBehavior() (opens new window) Attaches a behavior to this component.
attachBehaviors() (opens new window) Attaches a list of behaviors to the component.
beforeAction() This method is invoked right before an action is to be executed (after all possible filters.) It checks the existence of the migrationPath (opens new window).
behaviors() (opens new window) Returns a list of behaviors that this component should behave as.
bindActionParams() (opens new window) Binds the parameters to the action.
canGetProperty() (opens new window) Returns a value indicating whether a property can be read.
canSetProperty() (opens new window) Returns a value indicating whether a property can be set.
className() (opens new window) Returns the fully qualified name of this class.
confirm() (opens new window) Asks user to confirm by typing y or n.
createAction() (opens new window) Creates an action based on the given action ID.
detachBehavior() (opens new window) Detaches a behavior from the component.
detachBehaviors() (opens new window) Detaches all behaviors from the component.
ensureBehaviors() (opens new window) Makes sure that the behaviors declared in behaviors() (opens new window) are attached to this component.
findLayoutFile() (opens new window) Finds the applicable layout file.
getActionArgsHelp() (opens new window) Returns the help information for the anonymous arguments for the action.
getActionHelp() (opens new window) Returns the detailed help information for the specified action.
getActionHelpSummary() (opens new window) Returns a one-line short summary describing the specified action.
getActionOptionsHelp() (opens new window) Returns the help information for the options for the action.
getBehavior() (opens new window) Returns the named behavior object.
getBehaviors() (opens new window) Returns all behaviors attached to this component.
getHelp() (opens new window) Returns help information for this controller.
getHelpSummary() (opens new window) Returns one-line short summary describing this controller.
getMigrator() Returns the migration manager that should be used for this request
getModules() (opens new window) Returns all ancestor modules of this controller.
getOptionValues() (opens new window) Returns properties corresponding to the options for the action id Child classes may override this method to specify possible properties.
getPassedOptionValues() (opens new window) Returns the properties corresponding to the passed options.
getPassedOptions() (opens new window) Returns the names of valid options passed during execution.
getRoute() (opens new window) Returns the route of the current request.
getUniqueId() (opens new window) Returns the unique ID of the controller.
getView() (opens new window) Returns the view object that can be used to render views or view files.
getViewPath() (opens new window) Returns the directory containing view files for this controller.
hasEventHandlers() (opens new window) Returns a value indicating whether there is any handler attached to the named event.
hasMethod() (opens new window) Returns a value indicating whether a method is defined.
hasProperty() (opens new window) Returns a value indicating whether a property is defined.
init() Initializes the object.
isColorEnabled() (opens new window) Returns a value indicating whether ANSI color is enabled.
off() (opens new window) Detaches an existing event handler from this component.
on() (opens new window) Attaches an event handler to an event.
optionAliases() Returns option alias names.
options() Returns the names of valid options for the action (id) An option requires the existence of a public member variable whose name is the option name.
prompt() (opens new window) Prompts the user for input and validates it.
render() (opens new window) Renders a view and applies layout if available.
renderContent() (opens new window) Renders a static string by applying a layout.
renderFile() (opens new window) Renders a view file.
renderPartial() (opens new window) Renders a view without applying layout.
run() (opens new window) Runs a request specified in terms of a route.
runAction() (opens new window) Runs an action within this controller with the specified action ID and parameters.
select() (opens new window) Gives the user an option to choose from. Giving '?' as an input will show a list of options to choose from and their explanations.
setView() (opens new window) Sets the view object to be used by this controller.
setViewPath() (opens new window) Sets the directory that contains the view files.
stderr() (opens new window) Prints a string to STDERR.
stdout() (opens new window) Prints a string to STDOUT.
trigger() (opens new window) Triggers an event.

# actionAll()

Runs all pending Craft, plugin, and content migrations.

View source (opens new window)

Returns

integer (opens new window)

Throws

# actionCreate()

Creates a new migration.

This command creates a new migration using the available migration template. After using this command, developers should modify the created migration skeleton by filling up the actual migration logic.

craft migrate/create create_news_section

By default the migration will be created within the project's migrations/ folder (as a "content migration"). Use --plugin=<plugin-handle> to create a new plugin migration. Use --type=app to create a new Craft CMS app migration.

View source (opens new window)

Arguments

  • $name (string (opens new window)) – The name of the new migration. This should only contain letters, digits, and underscores.

Throws

# actionUp()

Upgrades the application by applying new migrations.

For example,

craft migrate     # apply all new migrations
craft migrate 3   # apply the first 3 new migrations

View source (opens new window)

Arguments

  • $limit (integer (opens new window)) – The number of new migrations to be applied. If 0, it means applying all available new migrations.

Returns

integer (opens new window) – The status of the action execution. 0 means normal, other values mean abnormal.

# beforeAction()

This method is invoked right before an action is to be executed (after all possible filters.) It checks the existence of the migrationPath (opens new window).

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether the action should continue to be executed.

Throws

# getMigrator()

Returns the migration manager that should be used for this request

View source (opens new window)

Returns

craft\db\MigrationManager

Throws

# init()

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

View source (opens new window)

# optionAliases()

Returns option alias names.

Child classes may override this method to specify alias options.

View source (opens new window)

Returns

array (opens new window) – The options alias names valid for the action where the keys is alias name for option and value is option name.

# options()

Returns the names of valid options for the action (id) An option requires the existence of a public member variable whose name is the option name.

Child classes may override this method to specify possible options.

Note that the values setting via options are not available until beforeAction() is being called.

View source (opens new window)

Arguments

Returns

string (opens new window)[] – The names of the options valid for the action

# Protected Methods

Method Description
addMigrationHistory() Adds new migration entry to the history.
bindInjectedParams() (opens new window) Fills parameters based on types and names in action method signature.
createMigration() Creates a new migration instance.
generateMigrationSourceCode() (opens new window) Generates new migration source PHP code.
getActionMethodReflection() (opens new window)
getMigrationHistory() Returns the migration history.
getMigrationNameLimit() (opens new window) Return the maximum name length for a migration.
getNewMigrations() Returns the migrations that are not applied.
includeMigrationFile() (opens new window) Includes the migration file for a given migration class name.
migrateDown() (opens new window) Downgrades with the specified migration class.
migrateToTime() (opens new window) Migrates to the specified apply time in the past.
migrateToVersion() (opens new window) Migrates to the certain version.
migrateUp() (opens new window) Upgrades with the specified migration class.
outputCommand()
parseDocCommentDetail() (opens new window) Returns full description from the docblock.
parseDocCommentSummary() (opens new window) Returns the first line of docblock.
parseDocCommentTags() (opens new window) Parses the comment block into tags.
removeMigrationHistory() Removes existing migration from the history.
truncateDatabase() Truncates the database.

# addMigrationHistory()

Adds new migration entry to the history.

View source (opens new window)

Arguments

# createMigration()

Creates a new migration instance.

View source (opens new window)

Arguments

Returns

yii\db\MigrationInterface (opens new window) – The migration instance

# getMigrationHistory()

Returns the migration history.

View source (opens new window)

Arguments

Returns

array (opens new window) – The migration history

# getNewMigrations()

Returns the migrations that are not applied.

View source (opens new window)

Returns

array (opens new window) – List of new migrations

# removeMigrationHistory()

Removes existing migration from the history.

View source (opens new window)

Arguments

# truncateDatabase()

Truncates the database.

This method should be overwritten in subclasses to implement the task of clearing the database.

View source (opens new window)

Throws

# Constants

Constant Description
BASE_MIGRATION The name of the dummy migration that marks the beginning of the whole migration history.
EXIT_CODE_ERROR
EXIT_CODE_NORMAL

# Events

# EVENT_REGISTER_MIGRATOR

Type
craft\events\RegisterMigratorEvent
Since
3.5.0

The event that is triggered when resolving an unknown migration track.

use craft\console\controllers\MigrateController;
use craft\db\MigrationManager;
use craft\events\RegisterMigratorEvent;
use yii\base\Event;

Event::on(
    MigrateController::class,
    MigrateController::EVENT_REGISTER_MIGRATOR,
    function(RegisterMigratorEvent $event) {
        if ($event->track === 'myCustomTrack') {
            $event->migrator = Craft::createObject([
                'class' => MigrationManager::class,
                'track' => 'myCustomTrack',
                'migrationNamespace' => 'my\migration\namespace',
                'migrationPath' => '/path/to/migrations',
            ]);
            $event->handled = true;
        }
    }
);