Magento2 Register 和 Registry

2018年11月2日 浏览量 31 1 min read
Magento2 Register 和 Registry

Magento注册表将数据存储到特定于该请求的内存(而不是用户或其他任何东西),并且仅在该请求的持续期间持有该数据。

由于对象是一个单体,所以无论何时访问它都会得到相同的对象。所有访问指的是您将值存储到这个对象,所以当一个类存储一个值而另一个类正访问它时,它们都在请求一个对象上,并且第二个类能够检索到第一个类存储的值。

在Magento1中,我们使用Mage::register()和Mage::registry(),但在Magento2中,实现略有不同,在这里我们使用Magento\Framework\Registry这个类,我们可以在任何构造函数中注入它,如下所示:

namespace Magease\Hello\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{ public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\Registry $registry) { $this->registry = $registry; return parent::__construct($context); } public function execute() { #some code here $this->registry->register('test_var', 'this is a test!'); #some code here } }

使用以下代码请求该变量:

$this->registry->registry('test_var');

基本上,您可以在控制器或block中注册一个变量,然后在任何地方访问它,如helper,block,model等,但这只能在同一个请求中。

注意: 我们将不得不再次将MagentoFramework\Registry类注入到要访问注册表的类的构造函数中。

Previous article:
Next article:
Comments
发表评论,留下你的足迹
我们不会公开你的邮箱地址

是否允许我们在发布新内容或者进行促销活动向您发送消息?

Remind me later

Thank you! Please check your email inbox to confirm.

Oops! Notifications are disabled.

© 2014-2023 www.magease.com. All Rights Reserved. 寰云网络 版权所有    鲁ICP备 14014975号-1