Controllers
A controller is where CakePHP brings a request together with your data. Once routing has decided which controller and action should run, the controller takes over: reading input, talking to models, and choosing what gets rendered back to the user.
Naming and Location
Controllers live in src/Controller/ and are named after the resource (plural)
they handle, with a Controller suffix. A controller for articles
is named ArticlesController and lives at:
src/Controller/ArticlesController.php
Every controller you write extends AppController, which in turn extends
CakePHP's own base Controller class. AppController is a good
place to put behavior shared across your whole application.
Actions Are Just Public Methods
An action is nothing more than a public method on a controller. Common
action names follow REST-ish conventions: index() for a listing,
view($id) for a single record, add() for creating a new one, and
so on. Whichever method matches the routed action name is the one that runs.
The Model Is Loaded Automatically
Thanks to convention over configuration — the same idea introduced on the
CakePHP Tutorial home page — ArticlesController
gets a ready-to-use $this->Articles property pointing at the
ArticlesTable model, with no manual wiring required.
Passing Data to the View
Once a controller action has the data it needs, it hands it off to the view with
$this->set(), giving the value a variable name the template can use:
$this->set('articles', $articles);
Inside the matching template, that data is then available simply as $articles.
A Full Worked Example
Here's a small but complete ArticlesController with an index()
action that lists all articles, and a view($id) action that loads one:
<?php
namespace App\Controller;
class ArticlesController extends AppController
{
// Lists every article
public function index()
{
$articles = $this->Articles->find()->all();
$this->set('articles', $articles);
}
// Shows a single article by id
public function view($id = null)
{
$article = $this->Articles->get($id);
$this->set('article', $article);
}
}
With this in place, a request to /articles runs index(), and a
request to /articles/view/5 runs view(5) — routing, the model, and
the controller all working together exactly as described in the previous two lessons.
$this->set() gets rendered into HTML.