magento 2에서 고객 세션 데이터를 설정하고 얻는 방법


12

magento 2 세션으로 어려움을 겪고 있습니다. 아래 컨트롤러 파일을 샘플 코드로 만들었습니다.

<?php
namespace vendor_name\module_name\Controller\SetGetSession;

use Magento\Framework\App\Action\Action;

class SetGetSession extends Action
{
    protected $customerSession;

    public function _construct(
        \Magento\Customer\Model\Session $customerSession
    ) {
        $this->customerSession = $customerSession;
    }   

    public function execute()
    {

    }
}

누구든지 데이터를 할당하고 세션 변수에서 데이터를 검색하는 방법을 도와 줄 수 있습니까?

감사합니다.

답변:


19

다음을 사용하여 고객 세션을 설정하고 얻을 수 있습니다 Magento\Customer\Model\Session

protected $customerSession;

public function __construct(   
    \Magento\Customer\Model\Session $customerSession
){
    $this->customerSession = $customerSession;
}

$this->customerSession->setMyValue('test');
$this->customerSession->getMyValue();

또는 객체 관리자에 의해.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
$customerSession->setMyValue('test');
$customerSession->getMyValue();
  1. 고객 세션에 정보 설정
$om = \Magento\Framework\App\ObjectManager::getInstance(); $session =
$om->get('Magento\Customer\Model\Session');  
$session->setTestKey('test value');
  1. 고객 세션에서 정보 얻기 :
$om = \Magento\Framework\App\ObjectManager::getInstance();  $session =
$om->get('Magento\Customer\Model\Session');
echo $session->getTestKey();

세션은 세션 Magento\Framework\Session\SessionManager을 처리하기 위해 핵심 클래스 를 확장 합니다.

이 답변이 도움이 되길 바랍니다.


제공된 set과 함께 "멤버 함수 setMyValue ()를 null로 호출"로 오류가 발생하고 세션 코드를 가져옵니다.
Aniket Shinde

객체 관리자가 추가 한 수정 된 답변을 확인하십시오.
Krishna ijjada

도와 주셔서 감사합니다. 객체 관리자와 함께 작동하지만 페이지로드 시간이 늘어나고있는 것 같습니다. 질문을 게시하기 전에 시도했습니다.
Aniket Shinde

3

\Magento\Customer\Model\Session세트에 클래스 를 주입 하고 고객 세션에서 데이터를 가져와야합니다.

의존성 주입 사용

protected $customerSession;

public function _construct(
    ...
    \Magento\Customer\Model\Session $customerSession
    ...
) {
    ...
    $this->customerSession = $customerSession;
    ...
}   

public function setValue()
{
    return $this->customerSession->setMyValue('YourValue'); //set value in customer session
}

public function getValue()
{
    return $this->customerSession->getMyValue(); //Get value from customer session
}

객체 관리자 사용

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$customerSession = $objectManager->get('Magento\Customer\Model\Session');

$customerSession->setMyValue('YourValue'); //set value in customer session
echo $customerSession->getMyValue(); //Get value from customer session
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.