controller.md 5.96 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`.
38 39 40
The output of an action is what the method returns. The return value will be handled by the `response` application
component which can convert the output to differnet formats such as JSON for example. The default behavior
is to output the value unchanged though.
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

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.

56 57 58
> 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`.

59 60 61 62 63 64
### 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.

65
A controller has a default action. When the user request does not specify which action to execute by using an URL such as
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
`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;

92
		if ($version) {
93 94 95
			$text = $post->getHistory($version);
		}

Alexander Makarov committed
96
		return $this->render('view', [
97 98
			'post' => $post,
			'text' => $text,
Alexander Makarov committed
99
		]);
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
	}
}
```

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);
124
		if (!$post) {
125
			throw new NotFoundHttpException;
126 127
		}

128
		if (\Yii::$app->request->isPost) {
129
			$post->load($_POST);
130
			if ($post->save()) {
Alexander Makarov committed
131
				$this->redirect(['view', 'id' => $post->id]);
132 133 134
			}
		}

Alexander Makarov committed
135
		return $this->render('update', ['post' => $post]);
136 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 162 163 164 165 166 167
	}
}
```

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
namespace \app\actions;

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

	public function run()
	{
		$this->controller->render($view);
	}
}
```

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
168 169
		return [
			'about' => [
170
				'class' => 'app\actions\Page',
Alexander Makarov committed
171 172 173
				'view' => 'about',
			],
		];
174 175 176 177 178 179
	}
}
```

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

180 181 182 183 184 185

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
186
as a behavior. For example, to use the [[AccessControl]] filter, you should have the following
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
code in a controller:

```php
public function behaviors()
{
    return [
        'access' => [
            'class' => 'yii\web\AccessControl',
            'rules' => [
                ['allow' => true, 'actions' => ['admin'], 'roles' => ['@']],
            ),
        ),
    );
}
```

203 204
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.
205 206 207 208

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

209 210
TDB

211 212 213
See also
--------

214
- [Console](console.md)