1

I am trying to retrieve customer data from the Customer session in ViewModel.

app/code/Magento/Module/ViewModel/Template.php

Due to FPC enabled, the session value is not retrieved. However, when I use Magento\Customer\Model\SessionFactory the values are updated and retrieved properly.

Below is the code snipped of sessionFactory

use Magento\Customer\Model\SessionFactory;

public function getCustomerId(): ?string
{
    $sessionObj = $this->customerSession->create();
    if($sessionObj->isLoggedIn())
    {
        return $sessionObj->getCustomerId();
    }
    return null;
}

Is it the correct way to retrieve Session data using SessionFactory? Also, is there any alternative better way to do so?

1
  • I think its better way. I tried to search for interface for it but was unable to find , so as of now for me its better and within the magento standard practicse.
    – Asssd
    Commented Nov 16, 2021 at 7:05

2 Answers 2

0

I don't see any problem with posted code. However, if you only need customer_id, this is an alternative which works fine with FPC

public function __construct(
    ...
    \Magento\Framework\App\Http\Context $httpContext,
    ...
) {
    $this->_httpContext = $httpContext;
    ...
}

public function getCustomerId()
{
    return $this->_httpContext->getValue('customer_id');
}
0

Using SessionFactory is a good way for checking customer is logged in in cached page.

Or you can chose another way by using Magento\Framework\App\Http\Context class.

Example

$this->context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH)

Hope it help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.