To implement Shopping cart or shopping basket, we need to store the shopping data in session. Here is the way how we can use simple session handling “Service” to implement it in Extbase extensions.
Below is the php code to handle sessions. The name of the php file will be “SessionHandler.php” and will be under folder EXT:myext/Classes/Domain/Service. We can identify this from namespace.
<?php
namespace TYPO3\Myext\Domain\Service;
class SessionHandler implements \TYPO3\CMS\Core\SingletonInterface {
public function restoreFromSession() {
$sessionData = unserialize($GLOBALS[‘TSFE’]->fe_user->getKey(‘ses’, ‘basket’));
if (mktime() >= $this->getSessionTimeout()) {
$this->cleanUpSession();
return null;
}
$this->setSessionTimeout();
return $sessionData;
}
public function writeToSession($object) {
$sessionData = serialize($object);
$GLOBALS[‘TSFE’]->fe_user->setKey(‘ses’, ‘basket’, $sessionData);
$GLOBALS[‘TSFE’]->fe_user->storeSessionData();
$this->setSessionTimeout();
return $this;
}
public function cleanUpSession() {
$GLOBALS[‘TSFE’]->fe_user->setKey(‘ses’, ‘basket’, NULL);
$GLOBALS[‘TSFE’]->fe_user->setKey(‘ses’, ‘basketLifetime’, NULL);
$GLOBALS[‘TSFE’]->fe_user->storeSessionData();
return $this;
}
public function setSessionTimeout() {
$GLOBALS[‘TSFE’]->fe_user->setKey(‘ses’, ‘basketLifetime’, mktime() + 600);
$GLOBALS[‘TSFE’]->fe_user->storeSessionData();
return $this;
}
public function getSessionTimeout() {
return $GLOBALS[‘TSFE’]->fe_user->getKey(‘ses’, ‘basketLifetime’);
}
}
So how to use these functions on our controllers ?
First we need to inject it in our controller like this
/**
* @var \TYPO3\Myext\Domain\Service\SessionHandler
* @inject
*/
protected $sessionHandler;
Then we can use below code in controller, for various actions on session.
Let us consider the variable “$basket” has the posted data from the forms. To store that data in session “basket”, below code will help.
$this->sessionHandler->writeToSession($basket);
To retrieve that data from session, we can use
$this->sessionHandler->restoreFromSession();
To cleanup the session,
$this->sessionHandler->cleanUpSession();
In the above php code, we can see that, I have set session timeout at 10 mins (600 secs).
If the user is loggedin, that user session timeout will be handled by
$TYPO3_CONF_VARS[“FE”][“lifetime”] = 600