Controller ​
- Type
- Class
- Namespace
- craft\console
- Inherits
- craft\console\Controller » yii\console\Controller » yii\base\Controller » yii\base\Component » yii\base\BaseObject
- Implements
- yii\base\Configurable, yii\base\ViewContextInterface
- Uses traits
- craft\console\ControllerTrait
- Extended by
- craft\console\controllers\BackupController, craft\console\controllers\BaseSystemStatusController, craft\console\controllers\ClearCachesController, craft\console\controllers\ClearDeprecationsController, craft\console\controllers\DbController, craft\console\controllers\ElementsController, craft\console\controllers\EntrifyController, craft\console\controllers\EntryTypesController, craft\console\controllers\EnvController, craft\console\controllers\ExecController, craft\console\controllers\FieldsController, craft\console\controllers\GcController, craft\console\controllers\GraphqlController, craft\console\controllers\IndexAssetsController, craft\console\controllers\InstallController, craft\console\controllers\InvalidateTagsController, craft\console\controllers\MailerController, craft\console\controllers\OffController, craft\console\controllers\OnController, craft\console\controllers\PcController, craft\console\controllers\PluginController, craft\console\controllers\ProjectConfigController, craft\console\controllers\ResaveController, craft\console\controllers\RestoreController, craft\console\controllers\SectionsController, craft\console\controllers\SetupController, craft\console\controllers\TestsController, craft\console\controllers\UpController, craft\console\controllers\UpdateController, craft\console\controllers\UsersController, craft\console\controllers\utils\AsciiFilenamesController, craft\console\controllers\utils\FixElementUidsController, craft\console\controllers\utils\FixFieldLayoutUidsController, craft\console\controllers\utils\PruneOrphanedEntriesController, craft\console\controllers\utils\PruneProvisionalDraftsController, craft\console\controllers\utils\PruneRevisionsController, craft\console\controllers\utils\RepairController, craft\console\controllers\utils\UpdateUsernamesController
- Since
- 3.2.0
Base console controller
Public Properties ​
Property | Description |
---|---|
action | yii\base\Action, null – The action that is currently being executed. |
behaviors | yii\base\Behavior – List of behaviors attached to this component. |
color | boolean, null – Whether to enable ANSI color in the output. |
defaultAction | string – The ID of the action that is used when the action ID is not specified in the request. |
help | boolean – Whether to display help information about current command. |
helpSummary | string – The one-line short summary describing this controller. |
id | string – The ID of this controller. |
interactive | boolean – Whether to run the command interactively. |
isolated | – Whether the command should ensure it is only being run once at a time. |
layout | string, null, false – The name of the layout to be applied to this controller's views. |
module | yii\base\Module – The module that this controller belongs to. |
modules | yii\base\Module – All ancestor modules that this controller is located within. |
passedOptionValues | array – The properties corresponding to the passed options. |
passedOptions | array – The names of the options passed during execution. |
request | craft\console\Request |
response | yii\base\Response, array, string – The response. |
route | string – The route (module ID, controller ID and action ID) of the current request. |
silentExitOnException | boolean, null – If true - script finish with ExitCode::OK in case of exception. |
uniqueId | string – The controller ID that is prefixed with the module ID (if any). |
view | yii\base\View, yii\web\View – The view object that can be used to render views or view files. |
viewPath | string – The directory containing the view files for this controller. |
request
​
- Type
- craft\console\Request
- Default value
null
Public Methods ​
Method | Description |
---|---|
__call() | Calls the named method which is not a class method. |
__clone() | This method is called after the object is created by cloning an existing one. |
__construct() | |
__get() | Returns the value of a component property. |
__isset() | Checks if a property is set, i.e. defined and not null. |
__set() | Sets the value of a component property. |
__unset() | Sets a component property to be null. |
actions() | Declares external actions for the controller. |
afterAction() | This method is invoked right after an action is executed. |
ansiFormat() | Formats a string with ANSI codes. |
attachBehavior() | Attaches a behavior to this component. |
attachBehaviors() | Attaches a list of behaviors to the component. |
beforeAction() | This method is invoked right before an action is executed. |
behaviors() | Returns a list of behaviors that this component should behave as. |
bindActionParams() | Binds the parameters to the action. |
canGetProperty() | Returns a value indicating whether a property can be read. |
canSetProperty() | Returns a value indicating whether a property can be set. |
className() | Returns the fully qualified name of this class. |
confirm() | Asks user to confirm by typing y or n. |
createAction() | Creates an action based on the given action ID. |
createDirectory() | Creates a directory, and outputs to the console. |
detachBehavior() | Detaches a behavior from the component. |
detachBehaviors() | Detaches all behaviors from the component. |
do() | Performs an action with descriptive output. |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. |
failure() | Outputs a failure message to the console. |
findLayoutFile() | Finds the applicable layout file. |
getActionArgsHelp() | Returns the help information for the anonymous arguments for the action. |
getActionHelp() | Returns the detailed help information for the specified action. |
getActionHelpSummary() | Returns a one-line short summary describing the specified action. |
getActionOptionsHelp() | Returns the help information for the options for the action. |
getBehavior() | Returns the named behavior object. |
getBehaviors() | Returns all behaviors attached to this component. |
getHelp() | Returns help information for this controller. |
getHelpSummary() | Returns one-line short summary describing this controller. |
getModules() | Returns all ancestor modules of this controller. |
getOptionValues() | Returns properties corresponding to the options for the action id Child classes may override this method to specify possible properties. |
getPassedOptionValues() | Returns the properties corresponding to the passed options. |
getPassedOptions() | Returns the names of valid options passed during execution. |
getRoute() | Returns the route of the current request. |
getUniqueId() | Returns the unique ID of the controller. |
getView() | Returns the view object that can be used to render views or view files. |
getViewPath() | Returns the directory containing view files for this controller. |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. |
hasMethod() | Returns a value indicating whether a method is defined. |
hasProperty() | Returns a value indicating whether a property is defined for this component. |
init() | Initializes the object. |
isColorEnabled() | Returns a value indicating whether ANSI color is enabled. |
markdownToAnsi() | Converts Markdown to be better readable in console environments by applying some ANSI format. |
note() | Outputs a note to the console. |
off() | Detaches an existing event handler from this component. |
on() | 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. |
output() | Prints text to STDOUT appended with a carriage return (PHP_EOL). |
passwordPrompt() | Prompts the user for a password and validates it. |
prompt() | Prompts the user for input and validates it. |
render() | Renders a view and applies layout if available. |
renderContent() | Renders a static string by applying a layout. |
renderFile() | Renders a view file. |
renderPartial() | Renders a view without applying layout. |
run() | Runs a request specified in terms of a route. |
runAction() | Runs an action with the specified action ID and parameters. |
select() | 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() | Sets the view object to be used by this controller. |
setViewPath() | Sets the directory that contains the view files. |
stderr() | Prints a string to STDERR. |
stdout() | Prints a string to STDOUT. |
success() | Outputs a success message to the console. |
table() | Outputs a table via craft\helpers\Console::table(). |
tip() | Outputs a tip to the console. |
trigger() | Triggers an event. |
warning() | Outputs a warning to the console. |
writeJson() | JSON-encodes a value and writes it to a file. |
writeToFile() | Writes contents to a file, and outputs to the console. |
__get()
​
Returns the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $component->property;
.
Arguments ​
$name
(string) – The property name
Returns ​
mixed
– The property value or the value of a behavior's property
Throws ​
- yii\base\UnknownPropertyException
if the property is not defined - yii\base\InvalidCallException
if the property is write-only.
__isset()
​
Checks if a property is set, i.e. defined and not null.
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
false
for non existing properties
Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property)
.
Arguments ​
$name
(string) – The property name or the event name
Returns ​
boolean – Whether the named property is set
__set()
​
Sets the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of "on xyz": attach the handler to the event "xyz"
- a behavior in the format of "as xyz": attach the behavior named as "xyz"
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $component->property = $value;
.
Arguments ​
$name
(string) – The property name or the event name$value
(mixed
) – The property value
Throws ​
- yii\base\UnknownPropertyException
if the property is not defined - yii\base\InvalidCallException
if the property is read-only.
actions()
​
Declares external actions for the controller.
This method is meant to be overwritten to declare external actions for the controller. It should return an array, with array keys being action IDs, and array values the corresponding action class names or action configuration arrays. For example,
return [
'action1' => 'app\components\Action1',
'action2' => [
'class' => 'app\components\Action2',
'property1' => 'value1',
'property2' => 'value2',
],
];
\Yii::createObject()
will be used later to create the requested action using the configuration provided here.
Returns ​
createDirectory()
​
- Since
- 4.3.5
Creates a directory, and outputs to the console.
Arguments ​
$path
(string) – The path to the directory
do()
​
- Since
- 4.3.5
Performs an action with descriptive output.
Arguments ​
$description
(string) – The action description. Supports Markdown formatting.$action
(callable) – The action callable$withDuration
(boolean) – Whether to output the action duration upon completion
getActionArgsHelp()
​
Returns the help information for the anonymous arguments for the action.
The returned value should be an array. The keys are the argument names, and the values are the corresponding help information. Each value must be an array of the following structure:
- required: bool, whether this argument is required
- type: string|null, the PHP type(s) of this argument
- default: mixed, the default value of this argument
- comment: string, the description of this argument
The default implementation will return the help information extracted from the Reflection or DocBlock of the parameters corresponding to the action method.
Arguments ​
$action
(yii\base\Action) – The action instance
Returns ​
array – The help information of the action arguments
getActionHelp()
​
Returns the detailed help information for the specified action.
Arguments ​
$action
(yii\base\Action) – Action to get help for
Returns ​
string – The detailed help information for the specified action.
getActionHelpSummary()
​
Returns a one-line short summary describing the specified action.
Arguments ​
$action
(yii\base\Action) – Action to get summary for
Returns ​
string – A one-line short summary describing the specified action.
getActionOptionsHelp()
​
Returns the help information for the options for the action.
The returned value should be an array. The keys are the option names, and the values are the corresponding help information. Each value must be an array of the following structure:
- type: string, the PHP type of this argument.
- default: string, the default value of this argument
- comment: string, the comment of this argument
The default implementation will return the help information extracted from the doc-comment of the properties corresponding to the action options.
Arguments ​
$action
(yii\base\Action)
Returns ​
array – The help information of the action options
init()
​
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
Throws ​
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.
Arguments ​
$actionID
(string) – The action id of the current request
Returns ​
string[] – The names of the options valid for the action
output()
​
- Since
- 5.5.0
Prints text to STDOUT appended with a carriage return (PHP_EOL).
Arguments ​
Returns ​
integer, false – The number of bytes printed or false on error
passwordPrompt()
​
- Since
- 3.6.0
Prompts the user for a password and validates it.
Arguments ​
$options
(array) – Options to customize the behavior of the prompt:label
: the prompt labelrequired
: whether it is required or not (true by default)validator
: a callable function to validate input. The function must accept two parameters:$input
: the user input to validate$error
: the error value passed by reference if validation failed
error
: the error message to show if the password is invalidconfirm
: whether the user should be prompted for the password a second time to confirm their input (true by default)
An example of how to use the prompt method with a validator function.
$code = $this->passwordPrompt('Enter 4-Chars-Pin', ['required' => true, 'validator' => function($input, &$error) {
if (strlen($input) !== 4) {
$error = 'The Pin must be exactly 4 chars!';
return false;
}
return true;
}]);
Returns ​
string – The user input
run()
​
Runs a request specified in terms of a route.
The route can be either an ID of an action within this controller or a complete route consisting of module IDs, controller ID and action ID. If the route starts with a slash '/', the parsing of the route will start from the application; otherwise, it will start from the parent module of this controller.
Arguments ​
$route
(string) – The route to be handled, e.g., 'view', 'comment/view', '/admin/comment/view'.$params
(array) – The parameters to be passed to the action.
Returns ​
mixed
– The result of the action.
runAction()
​
Runs an action with the specified action ID and parameters.
If the action ID is empty, the method will use defaultAction.
Arguments ​
$id
(string) – The ID of the action to be executed.$params
(array) – The parameters (name-value pairs) to be passed to the action.
Returns ​
integer – The status of the action execution. 0 means normal, other values mean abnormal.
Throws ​
- yii\base\InvalidRouteException
if the requested action ID cannot be resolved into an action successfully. - yii\console\Exception
if there are unknown options or missing arguments
stdout()
​
Prints a string to STDOUT.
You may optionally format the string with ANSI codes by passing additional parameters using the constants defined in yii\helpers\Console.
Example:
$this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
Arguments ​
$string
(string) – The string to print
Returns ​
integer, boolean – Number of bytes printed or false on error
table()
​
- Since
- 3.7.23
Outputs a table via craft\helpers\Console::table().
Arguments ​
$headers
(string[], array[]) – The table headers$data
(array[]) – The table data$options
(array)
writeJson()
​
- Since
- 4.3.5
JSON-encodes a value and writes it to a file.
Arguments ​
$file
(string) – The path to the file to write to$value
(mixed
) – The value to be JSON-encoded and written out
writeToFile()
​
- Since
- 4.3.5
Writes contents to a file, and outputs to the console.
Arguments ​
$file
(string) – The path to the file to write to$contents
(string) – The file contents$options
(array) – Options for craft\helpers\FileHelper::writeToFile()
Protected Methods ​
Method | Description |
---|---|
bindInjectedParams() | Fills parameters based on types and names in action method signature. |
checkRootUser() | Returns whether a command should be executed depending on whether it's being run as a root user, and whether they're OK with that. |
checkTty() | Sets yii\console\Controller::$interactive to false if this isn’t a TTY shell. |
createAttributeValidator() | Creates a function for the validator option of Controller::prompt . |
defineActions() | Returns an array of custom actions that should be available on the controller. |
getActionMethodReflection() | |
outputCommand() | |
parseDocCommentDetail() | Returns full description from the docblock. |
parseDocCommentSummary() | Returns the first line of docblock. |
parseDocCommentTags() | Parses the comment block into tags. |
defineActions()
​
Returns an array of custom actions that should be available on the controller.
The keys of this array should be the action IDs, and the values can be callables or sub-arrays with the following keys:
action
– A callable that is responsible for running the actionoptions
– An array of options that should be available to the command. Options can either be defined as strings (['option1', 'option2']
) or key/value pairs (['option1' => 'defaultValue']
).helpSummary
– Help summary text for the action (shown when runningcraft help controller-id
)help
– Help text for the action (shown when runningcraft help controller-id/action-id
)argsHelp
– Sub-array that defines help text for the arguments, indexed by argument names (shown when runningcraft help controller-id/action-id
)optionsHelp
– Sub-array that defines help text for the options, indexed by option names (shown when runningcraft help controller-id/action-id
)
Returns ​
getActionMethodReflection()
​
Arguments ​
$action
(yii\base\Action)
Returns ​
Constants ​
Constant | Description |
---|---|
EXIT_CODE_ERROR | |
EXIT_CODE_NORMAL |
Events ​
EVENT_DEFINE_ACTIONS ​
The event that is triggered when defining custom actions for this controller.
See defineActions() for details on what to set on $event->actions
.
Example ​
use craft\events\DefineConsoleActionsEvent;
use craft\console\Controller;
use craft\console\controllers\ResaveController;
use yii\base\Event;
Event::on(ResaveController::class,
Controller::EVENT_DEFINE_ACTIONS,
function(DefineConsoleActionsEvent $event) {
$event->actions['products'] = [
'options' => ['type'],
'helpSummary' => 'Re-saves products.',
'action' => function($params): int {
// @var ResaveController $controller
$controller = Craft::$app->controller;
$criteria = [];
if ($controller->type) {
$criteria['type'] = explode(',', $controller->type);
}
return $controller->resaveElements(Product::class, $criteria);
}
];
}
);