TYPO3 Extbase 从 Session 中设置和获取值

4
我正在TYPO3 v6.1上编写一个Extbase扩展,并且这个扩展的功能是用于巴士票预订。我的计划是,用户将选择日期和座位数量,然后提交表单。
我打算将所选座位的日期和费率推送到会话(购物车)中,并在付款时从会话中获取这些值,付款后需要清除该特定会话。
简而言之,如何在Extbase中推送和检索来自会话的值?有什么建议吗?
谢谢。

有没有关于商店的Extbase扩展的示例? - Ganybhat-Satvam Software
4个回答

9
有不同的方法。最简单的方法是在会话中写作。
$GLOBALS['TSFE']->fe_user->setKey("ses","key",$value)

从会话中读取值。
$GLOBALS["TSFE"]->fe_user->getKey("ses","key")

更新 自 TYPO3 v10 起,使用 $GLOBALS["TSFE"] 已经过时,所以如果您需要解决方案,请参考 https://dev59.com/QnTYa4cB1Zd3GeqPpwac#76817091


1
在上述情况下,它将是“ses”而不是“user”,以获取已设置的值...谢谢。 - Mihir Bhatt
1
setKey 之后不要忘记 $GLOBALS['TSFE']->fe_user->storeSessionData(); - Hafenkranich
1
如果有人在搜索答案时找到了这个帖子,$GLOBALS['TSFE']已经过时。我的回答中有最新的解决方案。 - vaxul

5
我正在使用一个服务类来实现这个功能。
<?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;
    }

}
?>

将此类注入到您的控制器中

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

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

现在您可以像这样使用此会话处理程序。
// 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');

将Tx_EXTNAME和tx_extname重命名为您的扩展名,并注意将会话处理程序类放入正确的目录中(Classes-> Service-> SessionHandler.php)。

您可以存储任何数据,而不仅仅是对象。

希望对您有所帮助。


5

从Typo3 v7开始,您还可以复制原生会话处理程序(\TYPO3\CMS\Form\Utility\SessionUtility)用于表单,并根据需要进行更改。该类区分普通用户和已登录用户,并支持通过sessionPrefix分隔的多个会话数据。

我也做了同样的事情,将该类推广到更常见的目的。我只删除了一个方法,更改了变量名称并添加了hasSessionKey()方法。以下是我的完整示例:

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]);
}

}

不要忘记先调用 initSession 方法,在您想使用该类的任何方法时都需要这样做。


这是最佳方法。不需要额外的序列化/反序列化,TYPO3会话会自动处理。 - JKB

1

由于用户搜索类似于 typo3 extbase session data 的内容时会找到此线程,因此答案 ($GLOBALS['TSFE']) 已过时,在TYPO3 v11.5或v12.4中采用了现代方法来回答此问题。

<?php

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;

class CustomController extends ActionController
{
    /** @var FrontendUserAuthentication */
    protected $frontendUser;

    /**
     * Share $frontendUser to all actions.
     * initializeAction() instead of _construct() because we need the request object.
     */
    public function initializeAction(): void
    {
        parent::initializeAction();

        $this->frontendUser = $this->request->getAttribute('frontend.user');
    }

    /**
     * The first action which save some data in the frontend user session.
     *
     * @return ResponseInterface
     */
    public function firstAction(): ResponseInterface
    {
        $this->frontendUser->setAndSaveSessionData('myKey', 'myMixedData');

        // Do stuff...

        return $this->htmlResponse();
    }

    /**
     * The second action which fetches the data from the frontend user session.
     *
     * @return ResponseInterface
     */
    public function secondAction(): ResponseInterface
    {
        $this->frontendUser->getSessionData('myKey');
        
        // Do stuff...

        return $this->htmlResponse();
    }
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接