Magento 2 自定义会话不一致

Magento 2 custom sessions not consistent

我已经使用 this guide 创建了自己的 magento 会话,但是这些会话变化无常,快把我逼疯了!

我已经创建了一个会话函数列表,因此所有会话设置器、获取器和取消设置器都在使用会话模型。

例如,在我的app/code/MyModule/MySession/Model/Session.php文件

中有很多这样的函数
//Set the car model from the session
public function setSessionCarModel($value){
    return $this->_session->setCarModel($value);
}

//Get the car model from the session
public function getSessionCarModel(){
    return $this->_session->getCarModel();
}

//Unset the car model from the session
public function unsetSessionCarModel(){
    return $this->_session->unsCarModel();
}

然后我尝试在我网站的多个位置设置、获取和取消设置我的会话,其中有几个例子(我知道我不应该在 .phtml 文件中使用对象管理器之前注意到)

.phtml

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customSession = $objectManager->create('\MyModule\MySession\Model\Session');
$carModel = $customSession->getSessionCarModel();

Ajax 文件

namespace MyVendor\MyModule\Controller\Ajax;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory; 

class Index extends Action {
    protected $_customSession;

    public function __construct(
        Context $context,
        \MyModule\MySession\Model\Session $customSession
    )
    {
        parent::__construct($context);
        $this->_customSession = $customSession;
    }


    public function execute(){
            $this->_customSession->setSessionCarModel(1);
    }
}

还有网站上的多个其他地方,但出于某种原因,我的会话似乎不一致,这让我抓狂!

有时它根本不设置它们,有时它获取旧值等。

我实现自定义会话的方式有问题吗?

如果有人能帮助阐明这一点,我将不胜感激!

Magento Version - 2.3.2

Session Store method - Files

Mode - Development

phtml 文件中粘贴的代码会产生问题。因为你是直接使用对象管理器。这会产生不一致的结果,尤其是当您尝试访问依赖于应用程序上下文的信息时。 Session / Cookies 都是这样的例子。

在您的 phtml 文件中,您可以使用 JavaScript 查询您的 ajax 控制器并从那里获取会话数据。已经在这里写了一个类似的答案: