php - 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
会话存储方法 - 文件
模式 - 发展
解决方案
粘贴在 phtml 文件中的代码会出现问题。因为您直接使用对象管理器。这会产生不一致的结果,尤其是当您尝试访问取决于应用程序上下文的信息时。会话/Cookies 都是这样的例子。
在您的 phtml 文件中,您可以使用 JavaScript 来查询您的 ajax 控制器并从那里获取会话数据。已经在这里写了一个类似的答案:
推荐阅读
- azure-devops - TFS 2015 到 Azure DevOps 服务的迁移
- php - 当在分页页面中按更新时,我再次回到第一页
- web-scraping - ETL - 如何进入网站,输入一些参数并将文件(或网络数据)导出到数据库
- elasticsearch - ElasticSearch 路径层次分词器聚合
- next.js - TypeError: Invalid PostCSS Plugin found at: plugins[0]
- spring-boot - Zuul 反向代理和 Spring Boot 管理配置
- c# - 在 for 循环中附加事件处理程序时的错误值
- github - 邀请某人在 github 中使用管理员权限进行协作
- c++ - 链表只在调试中删除,在构建中不删除
- javascript - 我们如何制作一个带有滚动条的 div 元素,使其垂直滚动条顶部位置为 100px?