Magento 2 的 registry 是 Mageplaza 在此模块开发系列中要介绍的下一个主题。Magento 1 和Magento 2 授权您注册支持静态 registry 方法的全局变量。
为了实现这个,可能你在 Magento1 中使用过 Mage::register() 和 Mage::registry(),但是在现在的Magento 2 平台,在运行 registry 时有一些不同。要求您使用 \Magento\Framework\ 注册表,该注册表可以接受已恢复数据的设置和 registry 。但是,首先,您需要学习如何创建或使用自己自定义的 registry ,以及如何检索全局 Magento 2 registry 对象,例如当前产品(product),种类(category),cms 页面,cms 块等。
幸运的是,所有这些对象在本文中都会被引用。今天的主题将帮助您熟悉 Magento 2 registry 对象。
如何在 registry / register 中获取和设置自定义属性
/**
* @var \Magento\Framework\Registry
*/
protected $_registry;
/**
* ...
* ...
* @param \Magento\Framework\Registry $registry,
*/
public function __construct(
...,
...,
\Magento\Framework\Registry $registry,
...
) {
$this->_registry = $registry;
...
...
}
/**
* Setting custom variable in registry to be used
*
*/
public function setCustomVariable()
{
$this->registry->register('custom_var', 'Added Value');
}
/**
* Retrieving custom variable from registry
* @return string
*/
public function getCustomVariable()
{
return $this->registry->registry('custom_var');
}
如何获取当前产品,类别,CMS页面的 registry
/**
* @var \Magento\Framework\Registry
*/
protected $_registry;
/**
* ...
* ...
* @param \Magento\Framework\Registry $registry,
*/
public function __construct(
...,
...,
\Magento\Framework\Registry $registry,
...
) {
$this->_registry = $registry;
...
...
}
/**
* Return catalog product object
*
* @return \Magento\Catalog\Model\Product
*/
public function getProduct()
{
return $this->_registry->registry('current_product');
}
/**
* Return catalog current category object
*
* @return \Magento\Catalog\Model\Category
*/
public function getCurrentCategory()
{
return $this->_registry->registry('current_category');
}
/**
* Return catalog current cms page object
*
*/
public function getCurrentCategory()
{
return $this->_registry->registry('current_cms_page');
}
通过本文的介绍,您就可以获取 Magento 2 registry 的内容。