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 = MagentoFrameworkAppObjectManager::getInstance();
$customSession = $objectManager->create('MyModuleMySessionModelSession');
$carModel = $customSession->getSessionCarModel();

阿贾克斯文件

namespace MyVendorMyModuleControllerAjax;
use MagentoFrameworkAppActionAction;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkControllerResultFactory; 
class Index extends Action {
protected $_customSession;
public function __construct(
Context $context,
MyModuleMySessionModelSession $customSession
)
{
parent::__construct($context);
$this->_customSession = $customSession;
}

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

以及网站上的多个其他地方,但由于某种原因,我的会话似乎不一致,这让我发疯!

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

我在实施自定义会话的方式上做错了什么吗?

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

马本托版本 - 2.3.2

会话存储方法 - 文件

模式 - 开发

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

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

Magento 2 会话自行取消设置

最新更新