cookie and session

本文深入探讨了Magento框架中Cookie和Session的管理机制。详细介绍了如何使用Magento框架的组件来创建、读取和删除Cookie,以及如何在不同的模块中管理和操作Session。通过具体代码示例,展示了Magento中Cookie与Session的高级用法。

一、cookie

protected $_cookieManager;

private $_cookieMetadataFactory;

private $_sessionManager;

public function __construct(

    \Magento\Framework\Stdlib\Cookie\PhpCookieManager $cookieManager,

    \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory,
    \Magento\Framework\Session\SessionManagerInterface $sessionManager

) {

        $this->_cookieManager = $cookieManager;
        $this->_cookieMetadataFactory = $cookieMetadataFactory;
        $this->_sessionManager = $sessionManager;
}

public function execute(\Magento\Framework\Event\Observer $observer){

        //第一次访问,还没有cookie记录
        if ($this->_cookieManager->getCookie('olight_geoip') === null) {
            $metadata = $this->_cookieMetadataFactory
                                                ->createPublicCookieMetadata()
                                                ->setDuration(86400)
                                                ->setPath($this->_sessionManager->getCookiePath())
                                                ->setDomain($this->_sessionManager->getCookieDomain());
            $this->_cookieManager->setPublicCookie('olight_geoip',1,$metadata);

        }

        //删除cookie

        $this->_cookieManager->deleteCookie('olight_geoip');

}

 

二、session

session 列表

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

下面,以/magento/module-checkout/Model/Session.php为例

<?php

$checkoutSession = $this->_objectManager->create('Magento\Checkout\Model\Session');

//set session
$sessionName = 'setFatherDayCustomer'.$customerId;
$checkoutSession->$sessionName(true);
                
//get session
$sessionName = 'getFatherDayCustomer'.$customerId;
$fatherDayCustomer = $checkoutSession->$sessionName();

//unset session
$sessionName = 'unsFatherDayCustomer'.$customerId;
$checkoutSession->$sessionName();

?>

转载于:https://my.oschina.net/ganfanghua/blog/2875080

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值