Session data
In the TYPO3 frontend, data can be stored in the current user session.
The actual location where the data will be stored is determined by the Session storage configuration.
You can use the following methods in
Frontend
:
Frontend
User Authentication:: get Key ($type, $key) - Loads data from the session.
Frontend
User Authentication:: set Key ($type, $key, $data) - Saves data to the session as a string.
Frontend
User Authentication:: store Session Data () - Writes session data so it is available in the next request.
Example: Save shopping basket into user session
Let us assume we have an Extbase Controller for a shopping basket. We want to preserve the data the user enters before closing the browser window. This should also work for non logged-in users.
We can use
$this->request->get
to create a frontend user on the fly if none exists.
If no Frontend user is currently logged in, an anonymous frontend user will be created on the fly.
In the browser of the current user a session cookie will be set linking them to the anonymous frontend user.
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\Controller;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
class ShoppingCartController extends ActionController
{
public const FORM_SESSION = 'myextension_cart';
public function putItemAction(Item $item): ResponseInterface
{
// Fetch cart from session or create a new one
$cart = $this->getCartFromSession() ?? new Cart();
$cart->add($item);
$this->storeCartInSession($cart);
return $this->redirect('list');
}
public function list(): ResponseInterface
{
$this->view->assign('cart', $this->getCartFromSession());
return $this->htmlResponse();
}
private function getFrontendUser(): FrontendUserAuthentication
{
// This will create an anonymous frontend user if none is logged in
return $this->request->getAttribute('frontend.user');
}
private function storeCartInSession(Cart $cart): void
{
// We use type ses to store the data in the session
$this->getFrontendUser()->setKey('ses', self::FORM_SESSION, serialize($cart));
// Important: store session data! Or it is not available in the next request!
$this->getFrontendUser()->storeSessionData();
}
private function getCartFromSession(): ?Cart
{
$data = $this->getFrontendUser()->getKey('ses', self::FORM_SESSION);
if (is_string($data)) {
$cart = unserialize($data);
if ($cart instanceof Cart) {
return $cart;
}
}
return null;
}
}