Components

If a helper is reusable logic for the view layer, a component is its counterpart for the controller layer. Components hold logic that more than one controller needs — things like flashing a one-time message to the user, checking authentication, or rate-limiting requests — so you write that logic once and load it wherever it's needed instead of repeating it in every action.

Loading a Component

Components are loaded in a controller's initialize() method with loadComponent(). Once loaded, the component is available as a property on $this, the same pattern you saw with helpers in a template. The most commonly used built-in component is FlashComponent, which stores a short-lived message in the session so it can be shown once on the very next page.

<?php
namespace App\Controller;

class ArticlesController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('Flash');
    }
}

Using a Component in an Action

With Flash loaded, any action on that controller can call $this->Flash->success() or $this->Flash->error() to queue a message, which a layout typically renders near the top of the very next page the user sees:

public function add()
{
    $article = $this->Articles->newEmptyEntity();

    if ($this->request->is('post')) {
        $article = $this->Articles->patchEntity($article, $this->request->getData());

        if ($this->Articles->save($article)) {
            $this->Flash->success('The article has been saved.');

            return $this->redirect(['action' => 'index']);
        }

        $this->Flash->error('The article could not be saved. Please try again.');
    }

    $this->set('article', $article);
}

Notice this action combines everything from the last few pages: patchEntity() and save() from CRUD Operations, the validation that quietly runs during patchEntity() from Validation, and now a Flash message on top, telling the user what happened either way.

Writing Your Own Component

FlashComponent ships with CakePHP, but you can write your own for logic that's specific to your app and shared across multiple controllers — for example, a component that checks an API rate limit before every request and rejects the action early if a client has made too many calls. A custom component follows the same shape as the built-in ones: a class with an initialize() and whatever methods you need, loaded from any controller with loadComponent('ApiRateLimit').

Note: Like every example in this track, this code is correct and ready to copy into your own CakePHP project, but this website doesn't have CakePHP installed, so it isn't executed live here.
Next: Head to Best Practices, the final page of this track, for a checklist that ties everything you've learned together.