Controller
API reference › yii › web › Controller
2 subclasses
Controller is the base class of web controllers.
For more details and usage information on Controller, see the guide article on controllers.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$action | yii\<static>| | The action that is currently being executed. Default: null. | yii\ |
$actionParams | array | The parameters bound to the current action. Default: []. | Controller |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$defaultAction | string | The ID of the action that is used when the action ID is not specified in the request. Default: 'index'. | yii\ |
$enableCsrfValidation | bool | Whether to enable CSRF validation for the actions in this controller. Default: true. | Controller |
$id | string | The ID of this controller. Default: null. | yii\ |
$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\ |
$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\ |
$uniqueId read-only | string | The controller ID that is prefixed with the module ID (if any). | yii\ |
$view | View | The view object that can be used to render views or view files. | Controller |
$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\ |
asJson() | Send data formatted as JSON. | Controller |
asXml() | Send data formatted as XML. | 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 |
bindActionParamsToCallable() static | Resolves the parameters for an action’s invokable callable using the same scalar coercion, type validation, and DI rules as bindActionParams(). | 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\ |
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\ |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getModules() | Returns all ancestor modules of this controller. | yii\ |
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\ |
goBack() | Redirects the browser to the last visited page. | Controller |
goHome() | Redirects the browser to the home page. | Controller |
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\ |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
redirect() | Redirects the browser to the specified URL. | Controller |
refresh() | Refreshes the current page. | Controller |
render() | Renders a view and applies layout if available. | yii\ |
renderAjax() | Renders a view in response to an AJAX request. | Controller |
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 within this controller with the specified action ID and parameters. | yii\ |
setView() | Sets the view object to be used by this controller. | yii\ |
setViewPath() | Sets the directory that contains the view files. | yii\ |
trigger() | Triggers an event. | yii\ |
bindInjectedParams() protected final | Fills parameters based on types and names in action method signature. | yii\ |
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”$enableCsrfValidation
Section titled “$enableCsrfValidation ”public bool $enableCsrfValidation = trueWhether to enable CSRF validation for the actions in this controller.
CSRF validation is enabled only when both this property and Request::$enableCsrfValidation are true.
Method details
Section titled “Method details”asJson()
Section titled “asJson() ”public function asJson(mixed $data): yii\web\ResponseSend data formatted as JSON.
This method is a shortcut for sending data formatted as JSON. It will return the response application component after configuring the format and setting the data that should be formatted. A common usage will be:
return $this->asJson($data);Parameters
| Parameter | Type | Description |
|---|---|---|
$data | mixed | The data that should be formatted. |
Returns
Response: A response that is configured to send $data formatted as JSON.
Since
2.0.11
See also
asXml()
Section titled “asXml() ”public function asXml(mixed $data): yii\web\ResponseSend data formatted as XML.
This method is a shortcut for sending data formatted as XML. It will return the response application component after configuring the format and setting the data that should be formatted. A common usage will be:
return $this->asXml($data);Parameters
| Parameter | Type | Description |
|---|---|---|
$data | mixed | The data that should be formatted. |
Returns
Response: A response that is configured to send $data formatted as XML.
Since
2.0.11
See also
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 check the parameter names that the action requires and return the provided parameters according to the requirement. If there is any missing parameter, an exception will be thrown.
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
BadRequestHttpException: if there are missing or invalid parameters.
bindActionParamsToCallable()
Section titled “bindActionParamsToCallable() ”public static function bindActionParamsToCallable(ReflectionMethod $method, array $params, yii\base\Module|null $module = null): arrayResolves the parameters for an action’s invokable callable using the same scalar coercion, type validation,
and DI rules as bindActionParams().
Standalone actions extending Action use this static entry point so they get the exact same
HTTP-aware parameter handling as controller-hosted actions.
Parameters
| Parameter | Type | Description |
|---|---|---|
$method | ReflectionMethod | The reflected run() (or controller method) whose parameters are being bound. |
$params | array | Route parameters available for binding (typically $_GET/$_POST-derived). |
$module | yii\| | The module that should be queried for components and DI definitions when resolving non-builtin typed parameters. May be null for standalone resolution outside a module context. |
Returns
array: A tuple [positional args, named action params, named requested params] where the first item is passed to the callable, the second mirrors the controller’s actionParams, and the third is a description map for Yii::$app->requestedParams.
Throws
BadRequestHttpException: if a scalar parameter fails type coercion or a required parameter is missing.ServerErrorHttpException: if a typed dependency cannot be resolved by the container.
Since
22.0
goBack()
Section titled “goBack() ”public function goBack(string|array|null $defaultUrl = null): yii\web\ResponseRedirects the browser to the last visited page.
You can use this method in an action by returning the Response directly:
// stop executing this action and redirect to last visited pagereturn $this->goBack();For this function to work you have to set the return URL in appropriate places before.
Parameters
| Parameter | Type | Description |
|---|---|---|
$defaultUrl | string| | The default return URL in case it was not set previously. If this is null and the return URL was not set previously, Application::$homeUrl will be redirected to. Please refer to User::setReturnUrl() on accepted format of the URL. |
Returns
Response: The current response object
See also
goHome()
Section titled “goHome() ”public function goHome(): yii\web\ResponseRedirects the browser to the home page.
You can use this method in an action by returning the Response directly:
// stop executing this action and redirect to home pagereturn $this->goHome();Returns
Response: The current response object
redirect()
Section titled “redirect() ”public function redirect(string|array $url, int $statusCode = 302): yii\web\ResponseRedirects the browser to the specified URL.
This method is a shortcut to Response::redirect().
You can use it in an action by returning the Response directly:
// stop executing this action and redirect to login pagereturn $this->redirect(['login']);Parameters
| Parameter | Type | Description |
|---|---|---|
$url | string| | The URL to be redirected to. This can be in one of the following formats: - a string representing a URL (e.g. “https://example.com”) - a string representing a URL alias (e.g. “@example.com”) - an array in the format of [$route, (e.g. ['site/index',) Url::to() will be used to convert the array into a URL. Any relative URL that starts with a single forward slash ”/” will be converted into an absolute one by prepending it with the host info of the current request. |
$statusCode | int | The HTTP status code. Defaults to 302. See https://tools.ietf.org/html/rfc2616#section-10 for details about HTTP status code |
Returns
Response: The current response object
refresh()
Section titled “refresh() ”public function refresh(string $anchor = ''): yii\web\ResponseRefreshes the current page.
This method is a shortcut to Response::refresh().
You can use it in an action by returning the Response directly:
// stop executing this action and refresh the current pagereturn $this->refresh();Parameters
| Parameter | Type | Description |
|---|---|---|
$anchor | string | The anchor that should be appended to the redirection URL. Defaults to empty. Make sure the anchor starts with ’#’ if you want to specify it. |
Returns
Response: The response object itself
renderAjax()
Section titled “renderAjax() ”public function renderAjax(string $view, array $params = []): stringRenders a view in response to an AJAX request.
This method is similar to renderPartial() except that it will inject into
the rendering result with JS/CSS scripts and files which are registered with the view.
For this reason, you should use this method instead of renderPartial() to render
a view to respond to an AJAX request.
Parameters
| Parameter | Type | Description |
|---|---|---|
$view | string | The view name. Please refer to render() on how to specify a view name. |
$params | array | The parameters (name-value pairs) that should be made available in the view. |
Returns
string: The rendering result.