Jak ustawiać, pobierać i usuwać zmienne sesji w Magento 2?


33

Co odpowiada sesji w Magento 1

Mage::getSingleton('core/session')->setMyValue('test');
Mage::getSingleton('core/session')->unsMyValue();

To samo w Magento 2?

Odpowiedzi:


20

Znalazłem równoważny sposób na to w Magento2:

Mage::getSingleton('core/session')->setMyValue('test');
Mage::getSingleton('core/session')->unsMyValue();

Ustaw / Pobierz / Rozbieraj wartość w sesji głównej:

protected $_coreSession;

public function __construct(
    -----
    \Magento\Framework\Session\SessionManagerInterface $coreSession
    ){
    $this->_coreSession = $coreSession;
    ----
}

public function setValue(){
    $this->_coreSession->start();
    $this->_coreSession->setMessage('The Core session');
}

public function getValue(){
    $this->_coreSession->start();
    return $this->_coreSession->getMessage();
}

public function unSetValue(){
    $this->_coreSession->start();
    return $this->_coreSession->unsMessage();
}

W ten sposób możemy ustawić niestandardowe wartości, jeśli nasza wartość sesji nie jest powiązana z poniższymi sesjami:

  • \ Magento \ Backend \ Model \ Session
  • \ Magento \ Katalog \ Model \ Sesja
  • \ Magento \ Checkout \ Model \ Session
  • \ Magento \ Customer \ Model \ Session
  • \ Magento \ Newsletter \ Model \ Sesja

1
Ładne wyjaśnienie!
— Himmat Paliwal

@Sarfaraz, czy możemy ustawić sesję w kontrolerze i uzyskać dostęp do pliku bloku?
— jafar pinjar

czy możemy ustawić wartość całkowitą ?, pojawia się poniżej błędu, Obiekt klasy Magento \\ Framework \\ Sesja \\ Generic \\ Interceptor nie mógł zostać przekonwertowany na ciąg znaków
— jafar pinjar

57

W Magento 2 nie ma już nic core/session.
Są jednak te (mogą być także inne):

  • \Magento\Backend\Model\Session
  • \Magento\Catalog\Model\Session
  • \Magento\Checkout\Model\Session
  • \Magento\Customer\Model\Session
  • \Magento\Newsletter\Model\Session

Musisz stworzyć zależność dla sesji, której potrzebujesz w swoim bloku, kontrolerze lub czymkolwiek.
Weźmy na przykład \Magento\Catalog\Model\Session.

protected $catalogSession;
public function __construct(
    ....
    \Magento\Catalog\Model\Session $catalogSession, 
    ....
){
    ....
    $this->catalogSession = $catalogSession;
    ....
}

Następnie możesz użyć sesji katalogu wewnątrz klasy w następujący sposób:

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

[EDYCJA]
Nie należy używać sesji w szablonach.
Powinieneś utworzyć opakowania w klasie bloków, których szablony mogą używać do ustawiania / pobierania wartości.

Korzystając z powyższego przykładu, utwórz metody w bloku

public function setSessionData($key, $value)
{
    return $this->catalogSession->setData($key, $value);
}

public function getSessionData($key, $remove = false)
{
    return $this->catalogSession->getData($key, $remove);
}

Ale jeśli naprawdę chcesz użyć sesji w szablonie, możesz po prostu utworzyć opakowanie w swoim bloku, aby uzyskać sesję:

public function getCatalogSession()
{
    return $this->catalogSession;
}

Następnie możesz to zrobić w szablonie:

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

jak korzystać z sesji w pliku phtml?
— Rakesh Jesadiya,

@RakeshJesadiya. Zobacz moją aktualizację.
— Marius

1
@Rachunek. Nie wiem
— Marius

1
@Marius Myślę, że zapomniałeś wspomnieć, jak rozbroić zmienną sesji. Więc proszę o komentarz w tej sprawie. Czy to podobne Magento 1.9.xx czy jeszcze?
— Bhupendra Jadeja

2
Tak. To jak w 1.9. UżyjunsMyValue
— Marius

7

Są to wszystkie typy sesji w Magento 2

1)  \Magento\Catalog\Model\Session //vendor/magento/module-catalog/Model/Session.php

2) \Magento\Newsletter\Model\Session //vendor/magento/module-newsletter/Model/Session.php

3) \Magento\Persistent\Model\Session //vendor/magento/module-persistent/Model/Session.php

4) \Magento\Customer\Model\Session //vendor/magento/module-customer/Model/Session.php

5) \Magento\Backend\Model\Session //vendor/magento/module-backend/Model/Session.php

6) \Magento\Checkout\Model\Session //vendor/magento/module-checkout/Model/Session.php

Zgodnie ze standardem kodowania Magento 2 ECGM2 najpierw używasz klasy sesji, a następnie możesz przekazać ją do konstruktora, w przeciwnym razie ten błąd zostanie wyświetlony

Obiekt sesji NIE MOŻE być wymagany w konstruktorze. Można go przekazać tylko jako argument metody.

Oto jak ustawić i uzyskać dane w sesji

namespace vendor\module\..;

use Magento\Catalog\Model\Session as CatalogSession;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Checkout\Model\Session as CheckoutSession;
use \Magento\Framework\Session\SessionManagerInterface as CoreSession

class ClassName {
    ...

    protected $_coreSession;
    protected $_catalogSession;
    protected $_customerSession;
    protected $_checkoutSession;

    public function __construct(
        ....
        CoreSession $coreSession,
        CatalogSession $catalogSession,
        CustomerSession $customerSession,
        CheckoutSession $checkoutSession,
        ....
    ){
        ....
        $this->_coreSession = $coreSession;
        $this->_catalogSession = $catalogSession;
        $this->_checkoutSession = $checkoutSession;
        $this->_customerSession = $customerSession;

        ....
    }

    public function getCoreSession() 
    {
        return $this->_coreSession;
    }

    public function getCatalogSession() 
    {
        return $this->_catalogSession;
    }

    public function getCustomerSession() 
    {
        return $this->_customerSession;
    }

    public function getCheckoutSession() 
    {
        return $this->_checkoutSession;
    }
}

Aby ustawić wartość

$this->getCustomerSession()->setMyValue('YourValue');

Aby uzyskać wartość

$this->getCustomerSession()->getMyValue();

Dla Nieustawionej wartości sesji

$this->getCustomerSession()->unsMyValue();

@RobbieAverill Jeśli znalazłeś jakieś rozwiązanie z innych stron, które możesz udostępnić tutaj na StackOverflow, które nie jest nazywane kopiowaniem przeszłości. to się nazywa badania i rozwój. Czy rozumiesz?
— Prince Patel

1
W porządku, ale powinieneś przy tym przypisywać źródła
— Robbie Averill

1
@RobbieAverill, Tak, masz rację. Dziękuję za sugestię. Zaktualizowałem swoją odpowiedź.
— Prince Patel

Podczas korzystania z klienta otrzymuję ostrzeżenie „Obiekt konstruktora NIE MOŻE być żądany w obiekcie konstruktora. Można go przekazać tylko jako argument metody”. Jak to rozwiązać ?
— Sanjay Gohil

1
@SanjayGohil sprawdź moją zaktualizowaną odpowiedź. najpierw użyj klasy sesji i przekaż konstruktorowi, aby uniknąć tego błędu. ”NIE MOŻNA żądać obiektu sesji w konstruktorze. Można go przekazać tylko jako argument metodyczny ”
— Prince Patel
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.