Skip to content
PHP Ecosystem
Explore

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.

PropertyTypeDescriptionDefined by
$actionyii\base\Action<static>|nullThe action that is currently being executed. Default: null.yii\base\Controller
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$colorbool|nullWhether to enable ANSI color in the output. Default: null.Controller
$defaultActionstringThe ID of the action that is used when the action ID is not specified in the request. Default: 'index'.yii\base\Controller
$helpboolWhether to display help information about current command. Default: false. Available since 2.0.10.Controller
$helpSummary read-onlystringThe one-line short summary describing this controller.Controller
$idstringThe ID of this controller. Default: null.yii\base\Controller
$interactiveboolWhether to run the command interactively. Default: true.Controller
$layoutstring|null|falseThe name of the layout to be applied to this controller’s views. Default: null.yii\base\Controller
$moduleyii\base\TThe module that this controller belongs to. Default: null.yii\base\Controller
$modules read-onlyyii\base\Module[]All ancestor modules that this controller is located within.yii\base\Controller
$passedOptions read-onlyarrayThe names of the options passed during execution.Controller
$passedOptionValues read-onlyarrayThe properties corresponding to the passed options.Controller
$requestRequestThe request object.Controller
$responseResponseThe response object.Controller
$route read-onlystringThe route (module ID, controller ID and action ID) of the current request.yii\base\Controller
$silentExitOnExceptionbool|nullIf true - script finish with ExitCode::OK in case of exception. false - ExitCode::UNSPECIFIED_ERROR. Default: null. Available since 2.0.36.Controller
$uniqueId read-onlystringThe controller ID that is prefixed with the module ID (if any).yii\base\Controller
$viewyii\base\View|yii\web\ViewThe view object that can be used to render views or view files.yii\base\Controller
$viewPathstringThe directory containing the view files for this controller.yii\base\Controller
MethodDescriptionDefined by
__construct()yii\base\Controller
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
actions()Declares external actions for the controller.yii\base\Controller
afterAction()This method is invoked right after an action is executed.yii\base\Controller
ansiFormat()Formats a string with ANSI codes.Controller
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
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\base\Component
bindActionParams()Binds the parameters to the action.Controller
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
confirm()Asks user to confirm by typing y or n.Controller
createAction()Creates an action based on the given action ID.yii\base\Controller
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
findLayoutFile()Finds the applicable layout file.yii\base\Controller
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\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
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\base\Controller
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\base\Controller
getUniqueId()Returns the unique ID of the controller.yii\base\Controller
getView()Returns the view object that can be used to render views or view files.yii\base\Controller
getViewPath()Returns the directory containing view files for this controller.yii\base\Controller
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the object.yii\base\Controller
isColorEnabled()Returns a value indicating whether ANSI color is enabled.Controller
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
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\base\Controller
renderContent()Renders a static string by applying a layout.yii\base\Controller
renderFile()Renders a view file.yii\base\Controller
renderPartial()Renders a view without applying layout.yii\base\Controller
run()Runs a request specified in terms of a route.yii\base\Controller
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\base\Controller
setViewPath()Sets the directory that contains the view files.yii\base\Controller
stderr()Prints a string to STDERR.Controller
stdout()Prints a string to STDOUT.Controller
trigger()Triggers an event.yii\base\Component
bindInjectedParams() protected finalFills parameters based on types and names in action method signature.yii\base\Controller
getActionMethodReflection() protectedController
parseDocCommentDetail() protectedReturns full description from the docblock.Controller
parseDocCommentSummary() protectedReturns the first line of docblock.Controller
parseDocCommentTags() protectedParses the comment block into tags.Controller
EventTypeDescriptionDefined by
EVENT_BEFORE_ACTIONyii\base\ActionEventAn event raised right before executing a controller action. Event name: 'beforeAction'.yii\base\Controller
EVENT_AFTER_ACTIONyii\base\ActionEventAn event raised right after executing a controller action. Event name: 'afterAction'.yii\base\Controller
public bool|null $color = null

Whether to enable ANSI color in the output.

If not set, ANSI color will only be enabled for terminals that support it.

public bool|null $silentExitOnException = null

If true - script finish with ExitCode::OK in case of exception. false - ExitCode::UNSPECIFIED_ERROR.

Default: YII_ENV_TEST

Since

2.0.36

public function ansiFormat(string $string): string

Formats 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

ParameterTypeDescription
$stringstringThe string to be formatted

Returns

string

public function beforeAction(mixed $action): bool

This 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

ParameterTypeDescription
$actionmixedThe action to be executed.

Returns

bool: Whether the action should continue to run.

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

ParameterTypeDescription
$actionyii\base\Action<static>The action to be bound with parameters
$paramsarray<array-key, mixed>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
public function confirm(string $message, bool $default = false): bool

Asks 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

ParameterTypeDescription
$messagestringTo echo out before waiting for user input
$defaultboolThis value is returned if no selection is made.

Returns

bool: Whether user confirmed. Will return true if $interactive is false.

public function getActionArgsHelp(yii\base\Action<static> $action): array

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.

Parameters

ParameterTypeDescription
$actionyii\base\Action<static>The action instance

Returns

array: The help information of the action arguments

public function getActionHelp(yii\base\Action<static> $action): string

Returns the detailed help information for the specified action.

Parameters

ParameterTypeDescription
$actionyii\base\Action<static>Action to get help for

Returns

string: The detailed help information for the specified action.

public function getActionHelpSummary(yii\base\Action<static> $action): string

Returns a one-line short summary describing the specified action.

Parameters

ParameterTypeDescription
$actionyii\base\Action<static>Action to get summary for

Returns

string: A one-line short summary describing the specified action.

public function getActionOptionsHelp(yii\base\Action<static> $action): array

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.

Parameters

ParameterTypeDescription
$actionyii\base\Action<static>

Returns

array: The help information of the action options

public function getHelp(): string

Returns 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.

public function getHelpSummary(): string

Returns 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.

public function getOptionValues(string $actionID): array

Returns properties corresponding to the options for the action id Child classes may override this method to specify possible properties.

Parameters

ParameterTypeDescription
$actionIDstringThe action id of the current request

Returns

array: Properties corresponding to the options for the action

public function getPassedOptions(): array

Returns the names of valid options passed during execution.

Returns

array: The names of the options passed during execution

public function getPassedOptionValues(): array

Returns the properties corresponding to the passed options.

Returns

array: The properties corresponding to the passed options

public function isColorEnabled(resource $stream = \STDOUT): bool

Returns 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

ParameterTypeDescription
$streamresourceThe stream to check.

Returns

bool: Whether to enable ANSI style in output.

public function optionAliases(): array

Returns 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

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

ParameterTypeDescription
$actionIDstringThe action id of the current request

Returns

string[]: The names of the options valid for the action

public function prompt(string $text, array $options = []): string

Prompts the user for input and validates it.

Parameters

ParameterTypeDescription
$textstringPrompt string
$optionsarrayThe 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

public function runAction(string $id, array $params = []): mixed

Runs an action with the specified action ID and parameters.

If the action ID is empty, the method will use $defaultAction.

Parameters

ParameterTypeDescription
$idstringThe ID of the action to be executed.
$paramsarrayThe parameters (name-value pairs) to be passed to the action.

Returns

mixed: The result of the action.

Throws

See also

public function select(string $prompt, array $options = [], string|null $default = null): string

Gives the user an option to choose from. Giving ’?’ as an input will show a list of options to choose from and their explanations.

Parameters

ParameterTypeDescription
$promptstringThe prompt message
$optionsarrayKey-value array of options to choose from
$defaultstring|nullValue 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

public function stderr(string $string): int|bool

Prints 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

ParameterTypeDescription
$stringstringThe string to print

Returns

int|bool: Number of bytes printed or false on error

public function stdout(string $string): int|bool

Prints 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

ParameterTypeDescription
$stringstringThe string to print

Returns

int|bool: Number of bytes printed or false on error

protected function getActionMethodReflection(yii\base\Action<static> $action): ReflectionFunctionAbstract

Parameters

ParameterTypeDescription
$actionyii\base\Action<static>

Returns

ReflectionFunctionAbstract

protected function parseDocCommentDetail(ReflectionClass<static>|ReflectionProperty|ReflectionFunctionAbstract $reflection): string

Returns full description from the docblock.

Parameters

ParameterTypeDescription
$reflectionReflectionClass<static>|ReflectionProperty|ReflectionFunctionAbstract

Returns

string

protected function parseDocCommentSummary(ReflectionClass<static>|ReflectionProperty|ReflectionFunctionAbstract $reflection): string

Returns the first line of docblock.

Parameters

ParameterTypeDescription
$reflectionReflectionClass<static>|ReflectionProperty|ReflectionFunctionAbstract

Returns

string

protected function parseDocCommentTags(ReflectionClass<object>|ReflectionProperty|ReflectionFunctionAbstract $reflection): array

Parses the comment block into tags.

Parameters

ParameterTypeDescription
$reflectionReflectionClass<object>|ReflectionProperty|ReflectionFunctionAbstractThe comment block

Returns

array: The parsed tags