User logged in or not checking not works in other pages such as Product, Category and other static pages but its works well on customer pages like Dashboard, Address book, Orders etc…
Here is my helper: app/code/MyVendor/MyUserModule/Helper/Data.php
<?php
namespace MyVendor\MyUserModule\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Customer\Model\Session $customerSession
) {
$this->customerSession = $customerSession;
parent::__construct($context);
}
public function isLoggedIn()
{
return $this->customerSession->isLoggedIn();
}
public function userLoggedDetails()
{
return $this->customerSession->getCustomer();
}
}
?>
And phtml like this
<?php
$customerSession = $this->helper('MyVendor\MyUserModule\Helper\Data');
if($customerSession->isLoggedIn()) {
echo "Welcome ".$customerSession->userLoggedDetails()->getName();
}else{
echo "Login";
}
?>
Also I noticed logged in or not checking works well on all pages while call ObjectManager directly, like this way
$om = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $om->create('Magento\Customer\Model\Session');
but this method not recommended by experts, so should follow Constructor injecting proper method, Anyone know what I missed, please.
Best Answer
Finally I got the answer, the problem with block cache, to get real Magento session, specific block cache must be false!
I did following changes and worked well:
$this->_isScopePrivate = true;
in my __constructcacheable="false"
to my block which belongs-to my template .phtml