首页 > 解决方案 > Magento 2 自定义会话不一致

问题描述

我使用本指南创建了自己的 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();

阿贾克斯文件

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 版本 - 2.3.2

会话存储方法 - 文件

模式 - 发展

标签: phpsessionmagentomagento2

解决方案


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

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

Magento 2 会话自我解除


推荐阅读