[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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
<?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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?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'); } } |