浏览文章
文章信息
Magento2 自定义session|Magento2 add a custom session|Magento2 create a session class
13531
1、创建session类
Aiweline\PaymentGateway\Model\Session
<?php declare(strict_types=1); /** * 文件信息 * 作者:邹万才 * 网名:秋风雁飞(Aiweline) * 网站:www.aiweline.com/bbs.aiweline.com * 工具:PhpStorm * 日期:2021/6/1 * 时间:18:16 * 描述:此文件源码由Aiweline(秋枫雁飞)开发,请勿随意修改源码! */ namespace Aiweline\PaymentGateway\Model; class Session extends \Magento\Framework\Session\SessionManager { }2、利用依赖注入di.xml实现session依赖
Aiweline\PaymentGateway\etc\di.xml
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd" <!--自定义Session--> <virtualType name="Aiweline\PaymentGateway\Model\Session\Storage" type="Magento\Framework\Session\Storage"> <arguments> <argument name="namespace" xsi:type="string">aiweline_payment_gateway</argument> </arguments> </virtualType> <type name="Aiweline\PaymentGateway\Model\Session"> <arguments> <argument name="storage" xsi:type="object">Aiweline\PaymentGateway\Model\Session\Storage</argument> </arguments> </type </config>3、使用方法
直接在__construct()实例化使用
<?php declare(strict_types=1); /** * 文件信息 * 作者:邹万才 * 网名:秋风雁飞(Aiweline) * 网站:www.aiweline.com/bbs.aiweline.com * 工具:PhpStorm * 日期:2021/6/1 * 时间:17:45 * 描述:此文件源码由Aiweline(秋枫雁飞)开发,请勿随意修改源码! */ namespace Aiweline\PaymentGateway\Controller\B; use Aiweline\PaymentGateway\Exception\PaymentGatewayException; use Aiweline\PaymentGateway\Helper\Data; use Aiweline\PaymentGateway\Model\Session; use Magento\Framework\App\Action\Context; class PlaceOrder extends \Magento\Framework\App\Action\Action { /** * @var Data */ private $helper; /** * @var Context */ private $context; /** * @var Session */ private $session; /** * PlaceOrder 初始函数... * @param Data $helper * @param Context $context * @param Session $session */ function __construct( Data $helper, Context $context, Session $session ) { parent::__construct($context); $this->helper = $helper; $this->context = $context; $this->session = $session; } /** * @inheritDoc */ public function execute() { $this->session->setData('test',1); $this->session->getData('test'); ......