In Yii a controller is an object:
- It is responsible for handling a request and producing a response.
- You have to create a controller class.
- The controller class extends
yii\base\Controller. In practice it is better to extend one of the specialised classes:yii\web\Controller,yii\rest\Controller, oryii\console\Controller. - Controllers consist of actions — entry points an end user can request. A controller may have one or many actions.
- The controller class name must end with
Controller. - An action method name must start with
action. - The
Userpart inUserControlleris called the ControllerID.
Example
namespace app\controllers;
use yii\web\Controller;
class UserController extends Controller
{
public function actionHello()
{
return 'Hello, world!';
}
}
Configuration
The controller namespace is set on the application object:
$config = [
'controllerNamespace' => 'app\\controllers',
];
Setting the default controller:
$config = [
'defaultRoute' => 'main',
];
Standalone actions
If an action repeats across controllers, extract it into a separate class (a so-called standalone action) and declare it in actions().
Error handling action:
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
CAPTCHA action:
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
Behaviors (filters)
A behavior simply extends the functionality of a class.
Access control
Controls access to specific controller actions:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::class,
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
];
}
See authentication and authorization for details on access control filters and RBAC.
Verb filter
Restricts which HTTP methods (GET, POST, …) are allowed for specific actions:
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
'logout' => ['post'],
],
],
];
}
Saving data from forms
public function actionIndex()
{
$model = new Spreadsheet();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->save()) {
return $this->refresh();
}
}
return $this->render('index', ['model' => $model]);
}
Responses
The simplest possible response:
public function actionHello()
{
return 'Hello, world!';
}
JSON
use Yii;
use yii\web\Response;
public function actionChangeStatus($id, $status)
{
Yii::$app->response->format = Response::FORMAT_JSON;
$response = ['success' => false];
if ($spreadsheet = Spreadsheet::findOne($id)) {
$spreadsheet->status = $status;
if ($spreadsheet->save()) {
$response['success'] = true;
}
}
return $response;
}
Passing a route to an AJAX handler
Render the route into the form’s action attribute and read it back in JavaScript:
<form id="js-sign-up-form" action="<?= Url::to(['site/sign-up']) ?>">
...
</form>
$('#js-sign-up-form').on('submit', function (e) {
const form = $(this);
$.post({
url: form.attr('action'),
data: form.serialize()
});
e.preventDefault();
});
Redirects
Reload the same page:
return $this->refresh();
Go back to the previous page:
return $this->goBack();
// Remember where to return later:
Yii::$app->user->setReturnUrl(Yii::$app->request->url);
Andrew Dorokhov