如何设置和移除会话

本文主题:如何在 Magento 2 中设置和移除会话,将会帮助您了解通过运行代码快速设置和移除会话的方法,因为随着自定义 Magento 2 的开发,了解会话是非常有必要的。

首先,请看下面列出的 Magento 2 的会话类型:

vendor/magento/module-catalog/Model/Session.php
 
vendor/magento/module-newsletter/Model/Session.php
 
vendor/magento/module-persistent/Model/Session.php
 
vendor/magento/framework/Message/Session.php
 
vendor/magento/module-customer/Model/Session.php
 
vendor/magento/module-backend/Model/Session.php
 
vendor/magento/module-checkout/Model/Session.php

接下来,通过以下代码开始调用 Catalog,Customer 和 Checkout 会话。

<?php
namespace Mageplaza\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_catalogSession;
    protected $_customerSession;
    protected $_checkoutSession;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\Session $catalogSession,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Checkout\Model\Session $checkoutSession,
        array $data = []
    )
    {        
        $this->_catalogSession = $catalogSession;
        $this->_checkoutSession = $checkoutSession;
        $this->_customerSession = $customerSession;
        parent::__construct($context, $data);
    }
    
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }
        
    public function getCatalogSession() 
    {
        return $this->_catalogSession;
    }
    
    public function getCustomerSession() 
    {
        return $this->_customerSession;
    }
    
    public function getCheckoutSession() 
    {
        return $this->_checkoutSession;
    }    
}
?>

然后,通过 .phtml 文件,可以对 Catalog,Customer 和 Checkout 会话进行设置。

$block->getCatalogSession()->setMyName('Mageplaza');
echo $block->getCatalogSession()->getMyName() . '<br />'; // output: Mageplaza
 
$block->getCheckoutSession()->setTestData('Hello World');
echo $block->getCheckoutSession()->getTestData() . '<br />'; // output: Hello World
 
$block->getCheckoutSession()->setTestHello('Test Hello Value');
echo $block->getCheckoutSession()->getTestHello() . '<br />'; // output: Test Hello Value

如果要移除这些会话,请执行以下操作:

$block->getCatalogSession()->unsMyName();
$block->getCheckoutSession()->unsTestData();
$block->getCustomerSession()->unsTestHello();

特别的是,用户会话允许收集用户的信息,例如客户名称和邮箱。

// get customer data
if ($block->getCustomerSession()->isLoggedIn()) {
    $customerId = $block->getCustomerSession()->getCustomerId();
    $customerData = $block->getCustomerSession()->getCustomer();
    echo $customerId . '<br />';
    echo $customerData->getFirstname() . ' ' . $customerData->getLastname() . '<br />';
    echo $customerData->getEmail() . '<br />';
    print_r($block->getCustomerSession()->getCustomer()->getData());
}

Checkout(结账)会话可以显示价格信息。

// get checkout session data
echo $block->getCheckoutSession()->getQuoteId();
print_r($block->getCheckoutSession()->getQuote()->getData());

本教程翻译自Mageplaza模块开发系列,其他内容请点击下面链接: