Frage

If we need to get current customer sessions in a block, cacheable must be set to false in the layout XML. I am using \Magento\Customer\Model\SessionFactory $customerSession in my block but it is not working without cacheable false. Can someone tell me a recommended way to solve this problem?

War es hilfreich?

Lösung

If you have to show customer-specific data (private content) you would have to serve the specific content from the server instead of cache. So, best practice would be using cache hole punching to get the specific data using ajax.

Magento has a standard implementation for us to use called customer sections which maintains versioning of the private content in local storage and invalidates them to get correct data through ajax call.

You can study it here on devdocs - https://devdocs.magento.com/guides/v2.3/extension-dev-guide/cache/page-caching/private-content.html

Here is some more read for understanding the internal working of customer sections - Magento 2: how do customer sections / sections.xml work?

Andere Tipps

\Magento\Customer\Model\SessionFactory will not work if the FPC is enabled. You can use the below code in your block class to check the user logged in the cache.

/**
 * Http Context
 *
 * @var \Magento\Framework\App\Http\Context
 */
protected $_httpContext;

/**
 * @var \Magento\Customer\Model\Session
 */
protected $customerSession;

/**
 * Init container
 */
public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Framework\App\Http\Context $httpContext,
    \Magento\Customer\Model\Session $customerSession,
    array $data = []
) {
    parent::__construct(
        $context,
        $data
    );
    $this->customerSession = $customerSession;
    $this->_httpContext = $httpContext;
    $this->_isScopePrivate = true;
}

public function isLoggedIn()
{
    return $this->_httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}

/**
 * get customer name
 *
 * @return string
 */
public function getCustomerName()
{
    if ($this->customerSession->isLoggedIn()) {
        return $this->customerSession->getCustomer()->getName();
    }
    return '';
}

Call $block->isLoggedIn() or $block->getCustomerName() in your phtml file to check the user is logged in or not.

I hope it helps!!!

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit magento.stackexchange
scroll top