magento 2.0:设置会话变量


magento 2.0: set session variable

我想在自定义模块中设置一个会话变量。

我正在使用自定义模块控制器中的$_SESSION['product_id'] = "12";

当我尝试在configurable.phtml模板中获取此会话时,它找不到正确的值。

请让我知道如何正确设置会话变量,以及如何使用Magento 2.0 在模板中再次读取此会话值

这是块类。

<?php
namespace YourNamespace'YourModule'Block;
class YourModule extends 'Magento'Framework'View'Element'Template
{   
    protected $_catalogSession;
    public function __construct(
        'Magento'Backend'Block'Template'Context $context,       
        'Magento'Catalog'Model'Session $catalogSession,     
        array $data = []
    )
    {       
        $this->_catalogSession = $catalogSession;
        parent::__construct($context, $data);
    }
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }
    public function getCatalogSession() 
    {
        return $this->_catalogSession;
    }   
}
?>

现在,我们从模板(.phtml)文件设置并获取会话。

// set product id in catalog session
$block->getCatalogSession()->setProductId(12);
// get product id from catalog session
echo $block->getCatalogSession()->getProductId();
// unset session variable
$block->getCatalogSession()->unsProductId();