Controllers
A controller is a class that receives a request and prepares data for a page. Each of its public methods is called an action and is responsible for one page: the list of articles, a single article, the add form.
Where they live
Controllers are in the src/Controller folder. The class name is plural with the Controller ending, and the file name matches the class name.
Creating
bin/cake bake controller ArticlesThe command creates src/Controller/ArticlesController.php. If the articles table does not exist in the database yet, create the file by hand:
// src/Controller/ArticlesController.php
namespace App\Controller;
class ArticlesController extends AppController
{
public function index(): void
{
$this->set('title', 'Articles');
}
}The /articles address calls the index() action. The set() method passes the $title variable with the value "Articles" to the template.
The template of an action
There is no need to call the template explicitly: after the action the framework renders templates/Articles/index.php by itself. Create it:
<h1><?= h($title) ?></h1>Open /articles and the page shows the heading "Articles". Without this file you get a "Missing Template" error with a hint where to create it.
Several variables
public function index(): void
{
$title = 'Articles';
$articles = ['First article', 'Second article'];
$this->set(compact('title', 'articles'));
}The compact() function builds an array from variables with the given names. The template gets $title and $articles.
An action with an argument
public function view(int $id): void
{
$this->set('id', $id);
}The part of the address after the action name goes into the argument: /articles/view/5 calls view(5). The template of this action is templates/Articles/view.php.
Shared code
All controllers extend AppController from src/Controller/AppController.php. Whatever is needed on every page is written there:
// src/Controller/AppController.php
public function initialize(): void
{
parent::initialize();
$this->loadComponent('Flash');
}initialize() runs before any action. A component is a ready-made block of code for controllers; Flash shows messages such as "Article saved".
Common mistake
Every public method of a controller becomes an action and can be called by address. A helper method declared as public also opens in the browser, for example /articles/calculate-total. Declare methods that are not pages as protected or private.