Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Flash messages and sessions

A session is a storage for the data of one visitor that lives between requests: the server recognises the browser by a cookie and fetches its data. A flash message is a short text such as "Article saved" that is put into the session and shown once on the next page.

Where it is set up

The Flash component is loaded in src/Controller/AppController.php with the line $this->loadComponent('Flash'), so it is available in all controllers. The session works right away; there is no need to start it.

A message

// src/Controller/ArticlesController.php
if ($this->Articles->save($article)) {
    $this->Flash->success('The article has been saved.');
 
    return $this->redirect(['action' => 'index']);
}
 
$this->Flash->error('Check the form data.');

success() and error() write a message to the session. After the redirect it appears on the list page and disappears on the next navigation.

Output

Messages are rendered by the templates/layout/default.php layout:

<main>
    <?= $this->Flash->render() ?>
    <?= $this->fetch('content') ?>
</main>

Save an article and "The article has been saved." appears above the list.

Kinds of messages

CallMessage template
$this->Flash->success('…')templates/element/flash/success.php
$this->Flash->error('…')templates/element/flash/error.php
$this->Flash->warning('…')templates/element/flash/warning.php
$this->Flash->info('…')templates/element/flash/info.php

Each kind has an element in the templates/element/flash folder. To change how messages look, edit these files. Your own kind is created the same way: a flash/note.php file and a $this->Flash->note('…') call.

Writing to the session

public function view(int $id): void
{
    $session = $this->request->getSession();
 
    $session->write('lastArticle', $id);
 
    $this->set('article', $this->Articles->get($id));
}

getSession() returns the session object and write() stores a value under the name lastArticle.

Reading

public function index(): void
{
    $lastId = $this->request->getSession()->read('lastArticle');
 
    $this->set('lastId', $lastId);
    $this->set('articles', $this->Articles->find()->all());
}

Open any article, go back to the list, and $lastId holds its number. If there is no value, read() returns null.

Session methods

MethodWhat it does
write('key', $value)Stores a value
read('key')Reads a value or null
check('key')Checks whether a value exists
delete('key')Removes a value
consume('key')Reads and removes at once
destroy()Clears the whole session

A dot in the name creates nesting: write('Cart.items', []).

Common mistake

A message was written but the page does not show it. The reason is a layout without the $this->Flash->render() line: it is easy to lose when the standard layout is replaced with your own. Check the layout before looking for an error in the controller.

Thanks for reading!

Donate to the site — we work hard for you.