0

I am new to Magento 2 modules and would like to create a module to run the below class whenever someone accesses the homepage. I believe it would be easier if I converted this to an observer so I just wanted to confirm that that was as simple as reconfiguring the below code block.

<?php
namespace Webkul\Module\Controller\DemoController;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;

class DemoClass extends Action {
    private $remoteAddress;
    
    public function __construct(
        Context $context,
        RemoteAddress $remoteAddress
    ) {
        $this->remoteAddress = $remoteAddress;
        parent::__construct($context);
    }

    public function execute()
    {
        $ip = $this->remoteAddress->getRemoteAddress();
        echo "Visitor's IP = ".$ip;
    }
}
1
  • Is working for you??
    – Mital Shah
    Commented Apr 24, 2021 at 11:51

1 Answer 1

0

You can use event controller_action_postdispatch_cms_index_index for home page

  1. Create "events.xml" file inside your extension folder Vendor/Module/etc/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_postdispatch_cms_index_index">
        <observer name="mymodule_controller_home_action" instance="Vendor\Module\Observer\Home"  />
    </event> 
</config>
  1. Create Observer file "Home.php" under Vendor/Module/Observer/Home.php
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;

class Home implements ObserverInterface
{    
    protected $remoteAddress;    

    public function __construct(RemoteAddress $remoteAddress)
    {
        $this->remoteAddress = $remoteAddress;
    }
    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {        
        $controller = $observer->getControllerAction();
        $ip = $this->remoteAddress->getRemoteAddress();
        echo "Visitor's IP = ".$ip;
        return $this;
    }
}

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.