Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Controllers and actions

A controller is a class that accepts a request and returns a response. Every page is one of its methods, called an action. Usually one controller is responsible for one entity of the site: posts, comments, users.

Where a controller lives

Controllers are stored in the controllers folder. There is no dedicated command for creating one, so the file is created by hand. Create controllers/PostController.php:

// controllers/PostController.php
namespace app\controllers;
 
use yii\web\Controller;
 
class PostController extends Controller
{
    public function actionIndex(): string
    {
        return 'List of posts';
    }
}

Open http://localhost:8080/index.php?r=post/index and you will see the line "List of posts".

Naming rules

Yii finds a controller by its name, so the names must follow the rules:

  • the class name ends with Controller, and the file name equals the class name;
  • the namespace is app\controllers;
  • an action method is public and starts with action.

In a route the names are written in lower case, with words separated by a hyphen:

Class and methodRoute
PostController::actionIndex()post/index
PostController::actionView()post/view
PostController::actionCreateDraft()post/create-draft
BlogPostController::actionIndex()blog-post/index

Action parameters

Yii takes method arguments from URL parameters with the same names. Add a second action to PostController:

// controllers/PostController.php
public function actionView(int $id): string
{
    return "Post number $id";
}

The URL index.php?r=post/view&id=5 shows "Post number 5". Without the id parameter Yii returns the 400 "Bad Request" error, and id=abc gives 400 too, because the argument type is declared as int.

An argument with a default value becomes optional:

public function actionIndex(int $page = 1): string
{
    return "List of posts, page $page";
}

The default action

If the route names only the controller, the index action runs: ?r=post equals ?r=post/index. A URL without a route opens site/index, the home page. It can be replaced in config/web.php:

// config/web.php
$config = [
    'defaultRoute' => 'post/index',
    // ...
];

Now http://localhost:8080/ shows the list of posts.

What an action returns

Return valueResult
A stringThe text of the page
$this->render('index')A page from a template
$this->redirect(['post/index'])A redirect
$this->asJson([...])A JSON response

Templates, redirects and JSON are covered in the next lessons.

Common mistake

An action name of several words is written with a hyphen in the URL: the method actionCreateDraft() is the route post/create-draft, not post/createDraft. A request with the wrong name ends with a 404 error.

Thanks for reading!

Donate to the site — we work hard for you.