Controller
API reference › yii › console › Controller
7 subclasses
Controller is the base class of console command classes.
A console controller consists of one or several actions known as sub-commands.
Users call a console command by specifying the corresponding route which identifies a controller action.
The yii program is used when calling a console command, like the following:
yii <route> [--param1=value1 --param2 ...]where <route> is a route to a controller action and the params will be populated as properties of a command.
See options() for details.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$action | yii\<static>| | The action that is currently being executed. Default: null. | yii\ |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$color | bool| | Whether to enable ANSI color in the output. Default: null. | Controller |
$defaultAction | string | The ID of the action that is used when the action ID is not specified in the request. Default: 'index'. | yii\ |
$help | bool | Whether to display help information about current command. Default: false. Available since 2.0.10. | Controller |
$helpSummary read-only | string | The one-line short summary describing this controller. | Controller |
$id | string | The ID of this controller. Default: null. | yii\ |
$interactive | bool | Whether to run the command interactively. Default: true. | Controller |
$layout | string| | The name of the layout to be applied to this controller’s views. Default: null. | yii\ |
$module | yii\ | The module that this controller belongs to. Default: null. | yii\ |
$modules read-only | yii\[] | All ancestor modules that this controller is located within. | yii\ |
$passedOptions read-only | array | The names of the options passed during execution. | Controller |
$passedOptionValues read-only | array | The properties corresponding to the passed options. | Controller |
$request | Request | The request object. | Controller |
$response | Response | The response object. | Controller |
$route read-only | string | The route (module ID, controller ID and action ID) of the current request. | yii\ |
$silentExitOnException | bool| | If true - script finish with ExitCode::OK in case of exception. false - ExitCode::UNSPECIFIED_ERROR. Default: null. Available since 2.0.36. | Controller |
$uniqueId read-only | string | The controller ID that is prefixed with the module ID (if any). | yii\ |
$view | yii\|yii\ | The view object that can be used to render views or view files. | yii\ |
$viewPath | string | The directory containing the view files for this controller. | yii\ |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | yii\ | |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
actions() | Declares external actions for the controller. | yii\ |
afterAction() | This method is invoked right after an action is executed. | yii\ |
ansiFormat() | Formats a string with ANSI codes. | Controller |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
beforeAction() | This method is invoked right before an action is executed. | Controller |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
bindActionParams() | Binds the parameters to the action. | Controller |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
confirm() | Asks user to confirm by typing y or n. | Controller |
createAction() | Creates an action based on the given action ID. | yii\ |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
findLayoutFile() | Finds the applicable layout file. | yii\ |
getActionArgsHelp() | Returns the help information for the anonymous arguments for the action. | Controller |
getActionHelp() | Returns the detailed help information for the specified action. | Controller |
getActionHelpSummary() | Returns a one-line short summary describing the specified action. | Controller |
getActionOptionsHelp() | Returns the help information for the options for the action. | Controller |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getHelp() | Returns help information for this controller. | Controller |
getHelpSummary() | Returns one-line short summary describing this controller. | Controller |
getModules() | Returns all ancestor modules of this controller. | yii\ |
getOptionValues() | Returns properties corresponding to the options for the action id Child classes may override this method to specify possible properties. | Controller |
getPassedOptions() | Returns the names of valid options passed during execution. | Controller |
getPassedOptionValues() | Returns the properties corresponding to the passed options. | Controller |
getRoute() | Returns the route of the current request. | yii\ |
getUniqueId() | Returns the unique ID of the controller. | yii\ |
getView() | Returns the view object that can be used to render views or view files. | yii\ |
getViewPath() | Returns the directory containing view files for this controller. | yii\ |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the object. | yii\ |
isColorEnabled() | Returns a value indicating whether ANSI color is enabled. | Controller |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
optionAliases() | Returns option alias names. | Controller |
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. | Controller |
prompt() | Prompts the user for input and validates it. | Controller |
render() | Renders a view and applies layout if available. | yii\ |
renderContent() | Renders a static string by applying a layout. | yii\ |
renderFile() | Renders a view file. | yii\ |
renderPartial() | Renders a view without applying layout. | yii\ |
run() | Runs a request specified in terms of a route. | yii\ |
runAction() | Runs an action with the specified action ID and parameters. | Controller |
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. | Controller |
setView() | Sets the view object to be used by this controller. | yii\ |
setViewPath() | Sets the directory that contains the view files. | yii\ |
stderr() | Prints a string to STDERR. | Controller |
stdout() | Prints a string to STDOUT. | Controller |
trigger() | Triggers an event. | yii\ |
bindInjectedParams() protected final | Fills parameters based on types and names in action method signature. | yii\ |
getActionMethodReflection() protected | Controller | |
parseDocCommentDetail() protected | Returns full description from the docblock. | Controller |
parseDocCommentSummary() protected | Returns the first line of docblock. | Controller |
parseDocCommentTags() protected | Parses the comment block into tags. | Controller |
Events
Section titled “Events”| Event | Type | Description | Defined by |
|---|---|---|---|
EVENT_BEFORE_ACTION | yii\ | An event raised right before executing a controller action. Event name: 'beforeAction'. | yii\ |
EVENT_AFTER_ACTION | yii\ | An event raised right after executing a controller action. Event name: 'afterAction'. | yii\ |
Property details
Section titled “Property details”$color
Section titled “$color ”public bool|null $color = nullWhether to enable ANSI color in the output.
If not set, ANSI color will only be enabled for terminals that support it.
$silentExitOnException
Section titled “$silentExitOnException ”public bool|null $silentExitOnException = nullIf true - script finish with ExitCode::OK in case of exception. false - ExitCode::UNSPECIFIED_ERROR.
Default: YII_ENV_TEST
Since
2.0.36
Method details
Section titled “Method details”ansiFormat()
Section titled “ansiFormat() ”public function ansiFormat(string $string): stringFormats a string with ANSI codes.
You may pass additional parameters using the constants defined in Console.
Example:
echo $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);Parameters
| Parameter | Type | Description |
|---|---|---|
$string | string | The string to be formatted |
Returns
string
beforeAction()
Section titled “beforeAction() ”public function beforeAction(mixed $action): boolThis method is invoked right before an action is executed.
The method will trigger the EVENT_BEFORE_ACTION event. The return value of the method
will determine whether the action should continue to run.
In case the action should not run, the request should be handled inside of the beforeAction code
by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
If you override this method, your code should look like the following:
public function beforeAction($action){ // your custom code here, if you want the code to run before action filters, // which are triggered on the [[EVENT_BEFORE_ACTION]] event, e.g. PageCache or AccessControl
if (!parent::beforeAction($action)) { return false; }
// other custom code here
return true; // or false to not run the action}Parameters
| Parameter | Type | Description |
|---|---|---|
$action | mixed | The action to be executed. |
Returns
bool: Whether the action should continue to run.
bindActionParams()
Section titled “bindActionParams() ”public function bindActionParams(yii\base\Action<static> $action, array<array-key, mixed> $params): mixed[]Binds the parameters to the action.
This method is invoked by Action when it begins to run with the given parameters.
This method will first bind the parameters with the options
available to the action. It then validates the given arguments.
Parameters
| Parameter | Type | Description |
|---|---|---|
$action | yii\<static> | The action to be bound with parameters |
$params | array<array-key, | The parameters to be bound to the action |
Returns
mixed[]: The valid parameters that the action can run with.
Throws
Exception: if there are unknown options or missing arguments
confirm()
Section titled “confirm() ”public function confirm(string $message, bool $default = false): boolAsks user to confirm by typing y or n.
A typical usage looks like the following:
if ($this->confirm("Are you sure?")) { echo "user typed yes\n";} else { echo "user typed no\n";}Parameters
| Parameter | Type | Description |
|---|---|---|
$message | string | To echo out before waiting for user input |
$default | bool | This value is returned if no selection is made. |
Returns
bool: Whether user confirmed. Will return true if $interactive is false.
getActionArgsHelp()
Section titled “getActionArgsHelp() ”public function getActionArgsHelp(yii\base\Action<static> $action): arrayReturns 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$action | yii\<static> | The action instance |
Returns
array: The help information of the action arguments
getActionHelp()
Section titled “getActionHelp() ”public function getActionHelp(yii\base\Action<static> $action): stringReturns the detailed help information for the specified action.
Parameters
| Parameter | Type | Description |
|---|---|---|
$action | yii\<static> | Action to get help for |
Returns
string: The detailed help information for the specified action.
getActionHelpSummary()
Section titled “getActionHelpSummary() ”public function getActionHelpSummary(yii\base\Action<static> $action): stringReturns a one-line short summary describing the specified action.
Parameters
| Parameter | Type | Description |
|---|---|---|
$action | yii\<static> | Action to get summary for |
Returns
string: A one-line short summary describing the specified action.
getActionOptionsHelp()
Section titled “getActionOptionsHelp() ”public function getActionOptionsHelp(yii\base\Action<static> $action): arrayReturns 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$action | yii\<static> |
Returns
array: The help information of the action options
getHelp()
Section titled “getHelp() ”public function getHelp(): stringReturns help information for this controller.
You may override this method to return customized help. The default implementation returns help information retrieved from the PHPDoc comment.
Returns
string: The help information for this controller.
getHelpSummary()
Section titled “getHelpSummary() ”public function getHelpSummary(): stringReturns one-line short summary describing this controller.
You may override this method to return customized summary. The default implementation returns first line from the PHPDoc comment.
Returns
string: The one-line short summary describing this controller.
getOptionValues()
Section titled “getOptionValues() ”public function getOptionValues(string $actionID): arrayReturns properties corresponding to the options for the action id Child classes may override this method to specify possible properties.
Parameters
| Parameter | Type | Description |
|---|---|---|
$actionID | string | The action id of the current request |
Returns
array: Properties corresponding to the options for the action
getPassedOptions()
Section titled “getPassedOptions() ”public function getPassedOptions(): arrayReturns the names of valid options passed during execution.
Returns
array: The names of the options passed during execution
getPassedOptionValues()
Section titled “getPassedOptionValues() ”public function getPassedOptionValues(): arrayReturns the properties corresponding to the passed options.
Returns
array: The properties corresponding to the passed options
isColorEnabled()
Section titled “isColorEnabled() ”public function isColorEnabled(resource $stream = \STDOUT): boolReturns a value indicating whether ANSI color is enabled.
ANSI color is enabled only if $color is set true or is not set
and the terminal supports ANSI color.
Parameters
| Parameter | Type | Description |
|---|---|---|
$stream | resource | The stream to check. |
Returns
bool: Whether to enable ANSI style in output.
optionAliases()
Section titled “optionAliases() ”public function optionAliases(): arrayReturns option alias names.
Child classes may override this method to specify alias options.
Returns
array: The options alias names valid for the action where the keys is alias name for option and value is option name.
Since
2.0.8
See also
options()
Section titled “options() ”public function options(string $actionID): string[]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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$actionID | string | The action id of the current request |
Returns
string[]: The names of the options valid for the action
prompt()
Section titled “prompt() ”public function prompt(string $text, array $options = []): stringPrompts the user for input and validates it.
Parameters
| Parameter | Type | Description |
|---|---|---|
$text | string | Prompt string |
$options | array | The options to validate the input: - required: whether it is required or not - default: default value if no input is inserted by the user - pattern: regular expression pattern to validate user input - 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. An example of how to use the prompt method with a validator function. $code = $this->prompt(‘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
runAction()
Section titled “runAction() ”public function runAction(string $id, array $params = []): mixedRuns an action with the specified action ID and parameters.
If the action ID is empty, the method will use $defaultAction.
Parameters
| Parameter | Type | Description |
|---|---|---|
$id | string | The ID of the action to be executed. |
$params | array | The parameters (name-value pairs) to be passed to the action. |
Returns
mixed: The result of the action.
Throws
yii\base\InvalidRouteException: if the requested action ID cannot be resolved into an action successfully.Exception: if there are unknown options or missing arguments
See also
select()
Section titled “select() ”public function select(string $prompt, array $options = [], string|null $default = null): stringGives the user an option to choose from. Giving ’?’ as an input will show a list of options to choose from and their explanations.
Parameters
| Parameter | Type | Description |
|---|---|---|
$prompt | string | The prompt message |
$options | array | Key-value array of options to choose from |
$default | string| | Value to use when the user doesn’t provide an option. If the default is null, the user is required to select an option. |
Returns
string: An option character the user chose
stderr()
Section titled “stderr() ”public function stderr(string $string): int|boolPrints a string to STDERR.
You may optionally format the string with ANSI codes by
passing additional parameters using the constants defined in Console.
Example:
$this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);Parameters
| Parameter | Type | Description |
|---|---|---|
$string | string | The string to print |
Returns
int|bool: Number of bytes printed or false on error
stdout()
Section titled “stdout() ”public function stdout(string $string): int|boolPrints a string to STDOUT.
You may optionally format the string with ANSI codes by
passing additional parameters using the constants defined in Console.
Example:
$this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);Parameters
| Parameter | Type | Description |
|---|---|---|
$string | string | The string to print |
Returns
int|bool: Number of bytes printed or false on error
getActionMethodReflection()
Section titled “getActionMethodReflection() ”protected function getActionMethodReflection(yii\base\Action<static> $action): ReflectionFunctionAbstractparseDocCommentDetail()
Section titled “parseDocCommentDetail() ”protected function parseDocCommentDetail(ReflectionClass<static>|ReflectionProperty|ReflectionFunctionAbstract $reflection): stringReturns full description from the docblock.
Parameters
| Parameter | Type | Description |
|---|---|---|
$reflection | ReflectionClass<static>|ReflectionProperty|ReflectionFunctionAbstract |
Returns
string
parseDocCommentSummary()
Section titled “parseDocCommentSummary() ”protected function parseDocCommentSummary(ReflectionClass<static>|ReflectionProperty|ReflectionFunctionAbstract $reflection): stringReturns the first line of docblock.
Parameters
| Parameter | Type | Description |
|---|---|---|
$reflection | ReflectionClass<static>|ReflectionProperty|ReflectionFunctionAbstract |
Returns
string
parseDocCommentTags()
Section titled “parseDocCommentTags() ”protected function parseDocCommentTags(ReflectionClass<object>|ReflectionProperty|ReflectionFunctionAbstract $reflection): arrayParses the comment block into tags.
Parameters
| Parameter | Type | Description |
|---|---|---|
$reflection | ReflectionClass<object>|ReflectionProperty|ReflectionFunctionAbstract | The comment block |
Returns
array: The parsed tags