controller.md 7.29 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 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
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
------

Controller resides in application's `controllers` directory is is named like `SiteController.php` where `Site`
part could be anything describing a set of actions it contains.

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`.
Mark committed
38
The output of an action is what the method returns, it could be rendered result or it can be instance of ```yii\web\Response```, for [example](#custom-response-class).
Mark committed
39
The return value will be handled by the `response` application
40 41
component which can convert the output to differnet formats such as JSON for example. The default behavior
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 62

```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
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
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);
	}
}
```

81 82 83 84 85 86 87 88 89 90 91 92 93 94
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.

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

98 99 100 101 102 103
### 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.

104
A controller has a default action. When the user request does not specify which action to execute by using an URL such as
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 130
`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;

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

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

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);
163
		if (!$post) {
164
			throw new NotFoundHttpException;
165 166
		}

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

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

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

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

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

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

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

219 220 221 222 223 224

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
225
as a behavior. For example, to use the [[AccessControl]] filter, you should have the following
226 227 228 229 230 231 232 233 234 235
code in a controller:

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

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

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

248
TBD
249

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

276
- [Console](console.md)