You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TYPO3 10.4 如何实现与示例代码逻辑一致的session变量存取功能

TYPO3 10.4 Session变量存取实现方案

你之前使用的$GLOBALS['TSFE']->fe_user相关写法在TYPO3 10.4中仍然保持向下兼容,如果是临时改造旧代码可以直接沿用,官方更推荐使用上下文API/依赖注入的方式实现,避免直接依赖全局变量,符合TYPO3编码规范。


1. 兼容旧版代码的快速实现

如果是在已经完成TSFE初始化的前端请求场景下,原有代码可以直接使用:

// 存储session变量
$GLOBALS['TSFE']->fe_user->setKey('ses','country',$country);
$GLOBALS['TSFE']->storeSessionData();

// 读取session变量
$x = $GLOBALS['TSFE']->fe_user->getKey('ses','country');

注意事项:

  • 该写法仅适用于前端请求上下文,后端模块、命令行任务等无TSFE的场景无法使用
  • 调用storeSessionData才会将变更持久化到session中

2. 官方推荐标准实现(依赖注入方式)

适用于所有支持依赖注入的场景(控制器、自定义服务类等),是TYPO3 10+的标准编码方式:

use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;

class YourCustomService
{
    // PHP 8.0+ 可直接使用构造函数属性注入
    public function __construct(
        private readonly FrontendUserAuthentication $frontendUserAuthentication
    ) {}

    /**
     * 存储country到session
     */
    public function setCountrySession(string $country): void
    {
        $this->frontendUserAuthentication->setKey('ses', 'country', $country);
        $this->frontendUserAuthentication->storeSessionData();
    }

    /**
     * 从session读取country
     */
    public function getCountrySession(): ?string
    {
        return $this->frontendUserAuthentication->getKey('ses', 'country') ?: null;
    }
}

如果使用PHP 7.4版本,调整属性声明方式即可:

/** @var FrontendUserAuthentication */
private $frontendUserAuthentication;

public function __construct(FrontendUserAuthentication $frontendUserAuthentication)
{
    $this->frontendUserAuthentication = $frontendUserAuthentication;
}

特殊场景下无法使用依赖注入时,可以通过GeneralUtility获取实例:

$frontendUser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(FrontendUserAuthentication::class);

内容的提问来源于stack exchange,提问作者Largo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 01:36:03