Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

Magento 2注册和注册表

Magento 2授权您注册支持静态注册表方法的全局变量。

Magento 2注册表 Mageplaza在此模块开发系列中要介绍的下一个主题。Magento 1和Magento 2授权您注册支持静态注册表方法的全局变量。

要实现这,也许你曾经工作Mage::register()Mage::registry()在Magento 1,但是现在的Magento 2平台,存在运行注册表中的差异。您将需要申请\Magento\Framework\Registry,该申请接受还原数据的设置和注册表。但是,首先,您需要学习如何创建或使用自己的自定义注册表,还需要向您展示如何检索全局Magento 2注册表对象,例如当前产品,categorycms页面cms块等。

这很幸运,因为所有这些都将在这里引用。今天的主题将帮助您熟悉Magento 2注册表对象

请遵循以下代码段:

如何在注册表/注册中获取和设置自定义属性

/**
  * @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页面的注册表


/**
  * @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的最佳结果。感谢您的观看,希望您对此感到满意。

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论