structure-controllers.md 9.27 KB
Newer Older
1 2 3
Controller
==========

4
> Note: This section is under development.
Qiang Xue committed
5

6 7 8 9 10 11 12
Controller is one of the key parts of the application. It determines how to handle incoming request and creates a response.

Most often a controller takes HTTP request data and returns HTML, JSON or XML as a response.

Basics
------

Qiang Xue committed
13 14
Controller resides in application's `controllers` directory and is named like `SiteController.php`,
where the `Site` part could be anything describing a set of actions it contains.
15

16
The basic web controller is a class that extends [[yii\web\Controller]] and could be very simple:
17 18 19 20 21 22 23 24

```php
namespace app\controllers;

use yii\web\Controller;

class SiteController extends Controller
{
25 26 27 28 29 30 31 32 33 34 35
    public function actionIndex()
    {
        // will render view from "views/site/index.php"
        return $this->render('index');
    }

    public function actionTest()
    {
        // will just print "test" to the browser
        return 'test';
    }
36 37 38 39
}
```

As you can see, typical controller contains actions that are public class methods named as `actionSomething`.
Qiang Xue committed
40
The output of an action is what the method returns: it could be a string or an instance of [[yii\web\Response]], [for example](#custom-response-class).
Mark committed
41
The return value will be handled by the `response` application
Qiang Xue committed
42
component which can convert the output to different formats such as JSON for example. The default behavior
43
is to output the value unchanged though.
44

Mark committed
45

46 47 48 49
Routes
------

Each controller action has a corresponding internal route. In our example above `actionIndex` has `site/index` route
50
and `actionTest` has `site/test` route. In this route `site` is referred to as controller ID while `test` is action ID.
51 52

By default you can access specific controller and action using the `http://example.com/?r=controller/action` URL. This
53
behavior is fully customizable. For more details please refer to [URL Management](url.md).
54

55 56 57 58 59
If a controller is located inside a module, the route of its actions will be in the format of `module/controller/action`.

A controller can be located under a subdirectory of the controller directory of an application or module. The route
will be prefixed with the corresponding directory names. For example, you may have a `UserController` under `controllers/admin`.
The route of its `actionIndex` would be `admin/user/index`, and `admin/user` would be the controller ID.
60 61 62

In case module, controller or action specified isn't found Yii will return "not found" page and HTTP status code 404.

63
> Note: If module name, controller name or action name contains camelCased words, internal route will use dashes i.e. for
64 65
`DateTimeController::actionFastForward` route will be `date-time/fast-forward`.

66 67 68
### Defaults

If user isn't specifying any route i.e. using URL like `http://example.com/`, Yii assumes that default route should be
69
used. It is determined by [[yii\web\Application::defaultRoute]] method and is `site` by default meaning that `SiteController`
70 71
will be loaded.

72
A controller has a default action. When the user request does not specify which action to execute by using an URL such as
73
`http://example.com/?r=site`, the default action will be executed. By default, the default action is named as `index`.
74
It can be changed by setting the [[yii\base\Controller::defaultAction]] property.
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

Action parameters
-----------------

It was already mentioned that a simple action is just a public method named as `actionSomething`. Now we'll review
ways that an action can get parameters from HTTP.

### Action parameters

You can define named arguments for an action and these will be automatically populated from corresponding values from
`$_GET`. This is very convenient both because of the short syntax and an ability to specify defaults:

```php
namespace app\controllers;

use yii\web\Controller;

class BlogController extends Controller
{
94 95
    public function actionView($id, $version = null)
    {
Alexander Makarov committed
96
        $post = Post::findOne($id);
97 98 99 100 101 102 103 104 105 106 107
        $text = $post->text;

        if ($version) {
            $text = $post->getHistory($version);
        }

        return $this->render('view', [
            'post' => $post,
            'text' => $text,
        ]);
    }
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
}
```

The action above can be accessed using either `http://example.com/?r=blog/view&id=42` or
`http://example.com/?r=blog/view&id=42&version=3`. In the first case `version` isn't specified and default parameter
value is used instead.

### Getting data from request

If your action is working with data from HTTP POST or has too many GET parameters you can rely on request object that
is accessible via `\Yii::$app->request`:

```php
namespace app\controllers;

use yii\web\Controller;
use yii\web\HttpException;

class BlogController extends Controller
{
128 129
    public function actionUpdate($id)
    {
Alexander Makarov committed
130
        $post = Post::findOne($id);
131 132 133 134 135 136 137 138 139 140 141 142 143
        if (!$post) {
            throw new NotFoundHttpException();
        }

        if (\Yii::$app->request->isPost) {
            $post->load(Yii::$app->request->post());
            if ($post->save()) {
                return $this->redirect(['view', 'id' => $post->id]);
            }
        }

        return $this->render('update', ['post' => $post]);
    }
144 145 146 147 148 149 150 151 152 153
}
```

Standalone actions
------------------

If action is generic enough it makes sense to implement it in a separate class to be able to reuse it.
Create `actions/Page.php`

```php
Carsten Brandt committed
154
namespace app\actions;
155 156 157

class Page extends \yii\base\Action
{
158
    public $view = 'index';
159

160 161 162 163
    public function run()
    {
        return $this->controller->render($view);
    }
164 165 166 167 168 169 170
}
```

The following code is too simple to implement as a separate action but gives an idea of how it works. Action implemented
can be used in your controller as following:

```php
171
class SiteController extends \yii\web\Controller
172
{
173 174 175 176 177 178 179 180 181
    public function actions()
    {
        return [
            'about' => [
                'class' => 'app\actions\Page',
                'view' => 'about',
            ],
        ];
    }
182 183 184 185 186
}
```

After doing so you can access your action as `http://example.com/?r=site/about`.

187 188 189 190

Action Filters
--------------

191 192 193 194 195 196 197
You may apply some action filters to controller actions to accomplish tasks such as determining
who can access the current action, decorating the result of the action, etc.

An action filter is an instance of a class extending [[yii\base\ActionFilter]].

To use an action filter, attach it as a behavior to a controller or a module. The following
example shows how to enable HTTP caching for the `index` action:
198 199 200 201 202

```php
public function behaviors()
{
    return [
203
        'httpCache' => [
204
            'class' => \yii\filters\HttpCache::className(),
205 206 207 208 209
            'only' => ['index'],
            'lastModified' => function ($action, $params) {
                $q = new \yii\db\Query();
                return $q->from('user')->max('updated_at');
            },
zvon committed
210 211
        ],
    ];
212 213 214
}
```

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
You may use multiple action filters at the same time. These filters will be applied in the
order they are declared in `behaviors()`. If any of the filter cancels the action execution,
the filters after it will be skipped.

When you attach a filter to a controller, it can be applied to all actions of that controller;
If you attach a filter to a module (or application), it can be applied to the actions of any controller
within that module (or application).

To create a new action filter, extend from [[yii\base\ActionFilter]] and override the
[[yii\base\ActionFilter::beforeAction()|beforeAction()]] and [[yii\base\ActionFilter::afterAction()|afterAction()]]
methods. The former will be executed before an action runs while the latter after an action runs.
The return value of [[yii\base\ActionFilter::beforeAction()|beforeAction()]] determines whether
an action should be executed or not. If `beforeAction()` of a filter returns false, the filters after this one
will be skipped and the action will not be executed.

230 231
The [authorization](authorization.md) section of this guide shows how to use the [[yii\filters\AccessControl]] filter,
and the [caching](caching.md) section gives more details about the [[yii\filters\PageCache]] and [[yii\filters\HttpCache]] filters.
232 233
These built-in filters are also good references when you learn to create your own filters.

234 235 236 237

Catching all incoming requests
------------------------------

238 239 240 241 242
Sometimes it is useful to handle all incoming requests with a single controller action. For example, displaying a notice
when website is in maintenance mode. In order to do it you should configure web application `catchAll` property either
dynamically or via application config:

```php
243
return [
244 245 246 247 248 249 250 251
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    // ...
    'catchAll' => [ // <-- here
        'offline/notice',
        'param1' => 'value1',
        'param2' => 'value2',
    ],
252
]
253 254 255 256
```

In the above `offline/notice` refer to `OfflineController::actionNotice()`. `param1` and `param2` are parameters passed
to action method.
257

Mark committed
258 259 260 261 262 263 264 265 266 267 268
Custom response class
---------------------

```php
namespace app\controllers;

use yii\web\Controller;
use app\components\web\MyCustomResponse; #extended from yii\web\Response

class SiteController extends Controller
{
269 270 271 272 273 274 275 276 277
    public function actionCustom()
    {
        /*
         * do your things here
         * since Response in extended from yii\base\Object, you can initialize its values by passing in
         * __constructor() simple array.
         */
        return new MyCustomResponse(['data' => $myCustomData]);
    }
Mark committed
278 279 280
}
```

Mark committed
281 282 283
See also
--------

284
- [Console](console.md)