Magento 1的Mage::getSingleton('adminhtml/session_quote')在Magento 2中的对应代码咨询
Magento 1
Mage::getSingleton('adminhtml/session_quote') 转换为 Magento 2 写法 嘿,刚好对这块比较熟悉,来给你拆解一下:
在 Magento 1 里你用的 Mage::getSingleton('adminhtml/session_quote'),对应的 Magento 2 类是 Magento\Backend\Model\Session\Quote,这是后台会话中管理报价(quote)的核心类。
不过要注意,Magento 2 不再推荐静态调用的方式,最佳实践是使用依赖注入(DI),下面分两种情况给你示例:
1. 推荐:使用依赖注入(项目开发首选)
在你需要使用这个会话类的自定义类中,通过构造函数注入该类,而不是直接实例化:
<?php namespace Your\Namespace; use Magento\Backend\Model\Session\Quote as AdminSessionQuote; // 引入其他必要的类... class YourCustomClass { protected $adminSessionQuote; public function __construct( // 这里注入后台报价会话类 AdminSessionQuote $adminSessionQuote, // 其他依赖... ) { $this->adminSessionQuote = $adminSessionQuote; // 调用父类构造(如果有的话) // parent::__construct(...); } public function yourCustomMethod() { // 现在就可以像M1里那样使用了,比如获取当前quote $quote = $this->adminSessionQuote->getQuote(); // 其他操作,比如设置quote // $this->adminSessionQuote->setQuote($yourQuoteObject); } }
这种方式符合 Magento 2 的架构设计,代码更易测试、维护,也避免了静态调用带来的耦合问题。
2. 临时场景:使用 ObjectManager(不推荐)
如果是临时调试或者特殊场景需要快速获取实例,可以用 ObjectManager,但官方强烈不建议在生产代码中这么做,因为会破坏依赖注入的优势:
// 仅用于临时测试/调试 $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $adminSessionQuote = $objectManager->get(\Magento\Backend\Model\Session\Quote::class); // 使用方式和上面一致 $quote = $adminSessionQuote->getQuote();
总结一下,核心就是替换成 Magento\Backend\Model\Session\Quote 类,并且尽量用依赖注入的方式来使用它。
内容的提问来源于stack exchange,提问作者coderunner
相关产品推荐
相关产品推荐

