Backend Session-Handler mit Extbase

[Aktualisiert im April 2020] In einem aktuellen Projekt müssen in einem Backend-Modul Daten in die Session gespeichert und wieder ausgelesen werden. Dazu kann man sich einen einfachen Wrapper für getSessionData und setAndSaveSessionData in $GLOBALS[‚BE_USER‘] machen, beispielsweise als SessionService:

<?php
 
namespace Vendor\Package\Service;
 
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
 
class SessionService
{
 
    /**
     * @var string
     */
    protected $storageKey = 'tx_package';
 
    /**
     * @var BackendUserAuthentication
     */
    protected $backendUser = null;
 
    /**
     * SessionService constructor.
     */
    public function __construct()
    {
        $this->backendUser = $this->getBackendUserObject();
    }
 
    /**
     * @param string $key
     * @param mixed $value
     */
    public function set($key, $value): void
    {
        $data = $this->backendUser->getSessionData($this->storageKey);
        if(is_array($data)) {
            $data[$key] = $value;
        } else {
            $data = [$key => $value];
        }
        $this->backendUser->setAndSaveSessionData($this->storageKey, $data);
    }
 
    /**
     * @param string $key
     * @return mixed
     */
    public function get(string $key)
    {
        $data = $this->backendUser->getSessionData($this->storageKey);
 
        return $data[$key] ?? null;
    }
 
    /**
     * @param string $key
     */
    public function delete(string $key): void
    {
        $data = $this->backendUser->getSessionData($this->storageKey);
        unset($data[$key]);
        $this->backendUser->setAndSaveSessionData($this->storageKey, $data);
    }
 
    /** 
     * @param string $storageKey 
     */ 
    public function setStorageKey(string $storageKey) 
    { 
        $this->storageKey = $storageKey; 
    }
 
    /**
     * @return BackendUserAuthentication
     */
    protected function getBackendUserObject(): BackendUserAuthentication
    {
        return $GLOBALS['BE_USER'];
    }
}

Verwendung im Controller:

<?php
 
namespace Vendor\Package\Controller;
 
use Vendor\Package\Service\SessionService;
 
/**
 * @package Vendor\Package\Controller
 */
class FooController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
    /**
     * @var SessionService
     */
    protected $session;
 
    /**
     * @param SessionService $sessionService
     */
    public function injectSessionService(SessionService $sessionService)
    {
        $this->session = $sessionService;
    }
 
    /**
     * @return void 
     */
    public function indexAction(): void
    {
 
        $this->session->set('foo', 'bar');
        // ... 
        $foo = $this->session->get('foo');
    }
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert