controller.md 7.32 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
Controller
==========

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
11 12
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.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

The basic web controller is a class that extends [[\yii\web\Controller]] and could be very simple:

```php
namespace app\controllers;

use yii\web\Controller;

class SiteController extends Controller
{
	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';
	}
}
```

As you can see, typical controller contains actions that are public class methods named as `actionSomething`.
Qiang Xue committed
38
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
39
The return value will be handled by the `response` application
Qiang Xue committed
40
component which can convert the output to different formats such as JSON for example. The default behavior
41
is to output the value unchanged though.
42

Mark committed
43
You also can disable CSRF validation per controller and/or action, by setting its property:
Mark committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

```php
namespace app\controllers;

use yii\web\Controller;

class SiteController extends Controller
{
	public $enableCsrfValidation = false;

	public function actionIndex()
	{
		#CSRF validation will no be applied on this and other actions
	}

}
```

Mark committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
To disable CSRF validation per custom actions you can do:

```php
namespace app\controllers;

use yii\web\Controller;

class SiteController extends Controller
{
	public function beforeAction($action)
	{
		// ...set `$this->enableCsrfValidation` here based on some conditions...
		// call parent method that will check CSRF if such property is true.
		return parent::beforeAction($action);
	}
}
```

80 81 82 83 84 85 86 87 88 89 90 91 92 93
Routes
------

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

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

If controller is located inside a module its action internal route will be `module/controller/action`.

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

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

97 98 99 100 101 102
### Defaults

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

103
A controller has a default action. When the user request does not specify which action to execute by using an URL such as
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
`http://example.com/?r=site`, the default action will be executed. By default, the default action is named as `index`.
It can be changed by setting the [[\yii\base\Controller::defaultAction]] property.

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
{
	public function actionView($id, $version = null)
	{
		$post = Post::find($id);
		$text = $post->text;

130
		if ($version) {
131 132 133
			$text = $post->getHistory($version);
		}

Alexander Makarov committed
134
		return $this->render('view', [
135 136
			'post' => $post,
			'text' => $text,
Alexander Makarov committed
137
		]);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
	}
}
```

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
{
	public function actionUpdate($id)
	{
		$post = Post::find($id);
162
		if (!$post) {
163
			throw new NotFoundHttpException;
164 165
		}

166
		if (\Yii::$app->request->isPost) {
167
			$post->load($_POST);
168
			if ($post->save()) {
Alexander Makarov committed
169
				$this->redirect(['view', 'id' => $post->id]);
170 171 172
			}
		}

Alexander Makarov committed
173
		return $this->render('update', ['post' => $post]);
174 175 176 177 178 179 180 181 182 183 184
	}
}
```

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
185
namespace app\actions;
186 187 188 189 190 191 192

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

	public function run()
	{
Carsten Brandt committed
193
		return $this->controller->render($view);
194 195 196 197 198 199 200 201
	}
}
```

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
202
class SiteController extends \yii\web\Controller
203 204 205
{
	public function actions()
	{
Alexander Makarov committed
206 207
		return [
			'about' => [
208
				'class' => 'app\actions\Page',
Alexander Makarov committed
209 210 211
				'view' => 'about',
			],
		];
212 213 214 215 216 217
	}
}
```

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

218 219 220 221 222 223

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

Action filters are implemented via behaviors. You should extend from `ActionFilter` to
define a new filter. To use a filter, you should attach the filter class to the controller
224
as a behavior. For example, to use the [[yii\web\AccessControl]] filter, you should have the following
225 226 227 228 229 230 231 232 233 234
code in a controller:

```php
public function behaviors()
{
    return [
        'access' => [
            'class' => 'yii\web\AccessControl',
            'rules' => [
                ['allow' => true, 'actions' => ['admin'], 'roles' => ['@']],
zvon committed
235 236 237
            ],
        ],
    ];
238 239 240
}
```

241 242
In order to learn more about access control check the [authorization](authorization.md) section of the guide.
Two other filters, [[yii\web\PageCache]] and [[yii\web\HttpCache]] are described in the [caching](caching.md) section of the guide.
243 244 245 246

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

247
TBD
248

Mark committed
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
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
{
	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
272 273 274
See also
--------

275
- [Console](console.md)