I am trying to create a simple module based on this answer https://magento.stackexchange.com/a/125519/45358
I just need a function to check if customer is logged or not in a custom theme header.phtml. I am new to Magento 2 and I can't understand how this works. I tried by following some tutorials but I am getting a lot of errors, like class not found and many more. I just need a complete example and then I will understand how actually work.
Here all files in my module
app/code/George/Core
registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'George_Core',
__DIR__
);
Block/Userlogin/Login
<?php
namespace George\Core\Block\Userlogin;
class Login extends Magento\Framework\View\Element\Template
{
public function isCustomerLoggedIn()
{
return $this->_session->isLoggedIn();
}
}
Model/Index/Index.php
<?php
namespace George\Core\Model\Index;
class Index extends \Magento\Framework\App\Action\Action
{
protected $_session;
public function __construct(
\Magento\Customer\Model\Session $session,
) {
$this->_session = $session;
}
}
etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="George_Core" setup_version="0.0.1"/>
</config>
Also I found that need to add somewhere a preference, I understand that preference should be inside /etc/di.xml but how the actual di.xml file should look?
<preference for="Block\That\Renders\The\Template"
type="Vendor\Module\Block\Your\Custom\Block" />
Also in my case I can't understand which is Block\That\Renders\The\Template and Vendor\Module\Block\Your\Custom\Block
Now how can I call this inside custom theme header.phtml template, because if I try that, website stops loading.
if ($block->isCustomerLoggedIn()) {
// Customer is logged in
} else {
// Customer is not logged in
}
If someone can provide me a simple complete example will be very helpful.