主题如何在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;
}
}
?>
然后,通过Catalog,Customer和Checkout会话,可以从.phtml
文件中设置它们。
$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());
}
结帐会话将显示报价信息。
// get checkout session data
echo $block->getCheckoutSession()->getQuoteId();
print_r($block->getCheckoutSession()->getQuote()->getData());
这是在Magento 2中设置和取消设置会话的指南。如果您对文章或任何问题有任何疑问,请使用下面的评论部分!