Typo3 Extbase Set and Get values from Session

14,568

Solution 1

There are different ways. The simplest would be for writing in the session

$GLOBALS['TSFE']->fe_user->setKey("ses","key",$value)

and for reading values from the session

$GLOBALS["TSFE"]->fe_user->getKey("ses","key")

Solution 2

From Typo3 v7 you can also copy the native session handler (\TYPO3\CMS\Form\Utility\SessionUtility) for forms and change it to your needs. The Class makes a different between normal and logged in users and it support multiple session data seperated by the sessionPrefix.

I did the same and generalized the class for a more common purpose. I only removed one method, change the variables name and added the method hasSessionKey(). Here is my complete example:

use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;

/**
* Class SessionUtility
*
* this is just a adapted version from   \TYPO3\CMS\Form\Utility\SessionUtility,
* but more generalized without special behavior for form
*
*
*/
class SessionUtility {

/**
 * Session data
 *
 * @var array
 */
protected $sessionData = array();

/**
 * Prefix for the session
 *
 * @var string
 */
protected $sessionPrefix = '';

/**
 * @var TypoScriptFrontendController
 */
protected $frontendController;

/**
 * Constructor
 */
public function __construct()
{
    $this->frontendController = $GLOBALS['TSFE'];
}

/**
 * Init Session
 *
 * @param string $sessionPrefix
 * @return void
 */
public function initSession($sessionPrefix = '')
{
    $this->setSessionPrefix($sessionPrefix);
    if ($this->frontendController->loginUser) {
        $this->sessionData = $this->frontendController->fe_user->getKey('user', $this->sessionPrefix);
    } else {
        $this->sessionData = $this->frontendController->fe_user->getKey('ses', $this->sessionPrefix);
    }
}

/**
 * Stores current session
 *
 * @return void
 */
public function storeSession()
{
    if ($this->frontendController->loginUser) {
        $this->frontendController->fe_user->setKey('user', $this->sessionPrefix, $this->getSessionData());
    } else {
        $this->frontendController->fe_user->setKey('ses', $this->sessionPrefix, $this->getSessionData());
    }
    $this->frontendController->storeSessionData();
}

/**
 * Destroy the session data for the form
 *
 * @return void
 */
public function destroySession()
{
    if ($this->frontendController->loginUser) {
        $this->frontendController->fe_user->setKey('user', $this->sessionPrefix, null);
    } else {
        $this->frontendController->fe_user->setKey('ses', $this->sessionPrefix, null);
    }
    $this->frontendController->storeSessionData();
}

/**
 * Set the session Data by $key
 *
 * @param string $key
 * @param string $value
 * @return void
 */
public function setSessionData($key, $value)
{
    $this->sessionData[$key] = $value;
    $this->storeSession();
}

/**
 * Retrieve a member of the $sessionData variable
 *
 * If no $key is passed, returns the entire $sessionData array
 *
 * @param string $key Parameter to search for
 * @param mixed $default Default value to use if key not found
 * @return mixed Returns NULL if key does not exist
 */
public function getSessionData($key = null, $default = null)
{
    if ($key === null) {
        return $this->sessionData;
    }
    return isset($this->sessionData[$key]) ? $this->sessionData[$key] : $default;
}

/**
 * Set the s prefix
 *
 * @param string $sessionPrefix
 *
 */
public function setSessionPrefix($sessionPrefix)
{
    $this->sessionPrefix = $sessionPrefix;
}

/**
 * @param string $key
 *
 * @return bool
 */
public function hasSessionKey($key) {
    return isset($this->sessionData[$key]);
}

}

Don't forget to call the initSession first, every time you want use any method of this class

Solution 3

I'm using for this a service class.

<?php
class Tx_EXTNAME_Service_SessionHandler implements t3lib_Singleton {

    private $prefixKey = 'tx_extname_';

    /**
    * Returns the object stored in the user´s PHP session
    * @return Object the stored object
    */
    public function restoreFromSession($key) {
        $sessionData = $GLOBALS['TSFE']->fe_user->getKey('ses', $this->prefixKey . $key);
        return unserialize($sessionData);
    }

    /**
    * Writes an object into the PHP session
    * @param    $object any serializable object to store into the session
    * @return   Tx_EXTNAME_Service_SessionHandler this
    */
    public function writeToSession($object, $key) {
        $sessionData = serialize($object);
        $GLOBALS['TSFE']->fe_user->setKey('ses', $this->prefixKey . $key, $sessionData);
        $GLOBALS['TSFE']->fe_user->storeSessionData();
        return $this;
    }

    /**
    * Cleans up the session: removes the stored object from the PHP session
    * @return   Tx_EXTNAME_Service_SessionHandler this
    */
    public function cleanUpSession($key) {
        $GLOBALS['TSFE']->fe_user->setKey('ses', $this->prefixKey . $key, NULL);
        $GLOBALS['TSFE']->fe_user->storeSessionData();
        return $this;
    }

    public function setPrefixKey($prefixKey) {
    $this->prefixKey = $prefixKey;
    }

}
?>

Inject this class into your controller

/**
 *
 * @var Tx_EXTNAME_Service_SessionHandler
 */
protected $sessionHandler;

/**
 * 
 * @param Tx_EXTNAME_Service_SessionHandler $sessionHandler
 */
public function injectSessionHandler(Tx_EXTNAME_Service_SessionHandler $sessionHandler) {
    $this->sessionHandler = $sessionHandler;
}

Now you can use this session handler like this.

// Write your object into session
$this->sessionHandler->writeToSession('KEY_FOR_THIS_PROCESS');

// Get your object from session
$this->sessionHandler->restoreFromSession('KEY_FOR_THIS_PROCESS');

// And after all maybe you will clean the session (delete)
$this->sessionHandler->cleanUpSession('KEY_FOR_THIS_PROCESS');

Rename Tx_EXTNAME and tx_extname with your extension name and pay attention to put the session handler class into the right directory (Classes -> Service -> SessionHandler.php).

You can store any data, not only objects.

HTH

Share:
14,568
Ganybhat-Satvam Software
Author by

Ganybhat-Satvam Software

CEO of Kalpavruksha Technologies Private Limited.

Updated on June 15, 2022

Comments

  • Ganybhat-Satvam Software
    Ganybhat-Satvam Software almost 2 years

    I am writing an extbase extension on typo3 v6.1 That extension suppose to do a bus ticket booking. Here what my plan is, user will select date and number of seats and submit the form.

    Here my plan to push the date and rate of the selected seat to session (Basket). And while making payment, I wanted to get that values from session and after payment I need to clear that particular session.

    So In short, How to Push and retrieve the values to and from the session in extbase. Any suggestions ? Thank you.