5

I tried this code but when cache is disable. it works, but when I enable cache it does not work.

$ObjectManager = \Magento\Framework\App\ObjectManager::getInstance();
$session =  $ObjectManager->get('Magento\Customer\Model\Session');
if($session->isLoggedIn()) 
{
}
3
  • in which file you are using this code? Commented Dec 21, 2017 at 5:05
  • i created one custom file for My account link in Magento_Theme Folder Commented Dec 21, 2017 at 5:06
  • Magento discourages us to use Object Manager directly. Commented Dec 21, 2017 at 5:24

3 Answers 3

7

Use below code:

$ObjectManager= \Magento\Framework\App\ObjectManager::getInstance();
$context = $ObjectManager->get('Magento\Framework\App\Http\Context');
$isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
return $isLoggedIn;
9

The best practice is to use Magento\Framework\App\Http\Context to check the customer logged in or not. And, avoiding using Object Manager directly.

For example:

<?php

namespace Vendor\Customer\Block\Account;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\App\Http\Context as HttpContext;

class Customer extends Template
{
    /**
     * @var HttpContext
     */
    protected $httpContext;

    /**
     * @param Context $context
     * @param HttpContext $httpContext
     * @param array $data
     */
    public function __construct(
        Context $context,
        HttpContext $httpContext,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->httpContext = $httpContext;
    }

    /**
     * Checking customer login status
     *
     * @return bool
     */
    public function customerLoggedIn()
    {
        return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
    }
}
2
0

If you create() the session, exactly you can force to get the current customer session with full page cache enabled. But i am not sure what principle it is using.

    $app = $ObjectManager->get('Magento\Framework\App\Http\Context');

    if ($app->getValue('customer_logged_in')) {

        $customerSession = $ObjectManager->create('Magento\Customer\Model\SessionFactory')->create();

        $customerData = $customerSession->getData();

        $customerId = isset($customerData['customer_id'])?$customerData['customer_id']:'';
    }

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.