6

I have a function that retrieves a visiting user's country name by doing an ip lookup. I currently have this function running through the execute method in my module's controller. The problem is that I need this to run on every page and not just the single controller page.

Since every controller is tied to a particular action I am not sure if keeping it in a controller is the correct solution, nor do I know how to run my controller on every page request.

Does anybody know how to do this?

1
  • 1
    You should use an observer for this. Connect it to one of the controller dispatch events so it's fired on every front end page request
    – scrowler
    Jun 22, 2016 at 22:22

1 Answer 1

15

Per Robbie's suggestion I created:

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_predispatch">
      <observer name="my_observer" instance="Module\Path\To\MyClass" shared="false" />
  </event>
</config>

Then created observer class

<?php 

namespace Module\Namespace\Path;

use Magento\Framework\Event\ObserverInterface;

class MyClass implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
   {
       // insert code here
   }

}

From here I injected the required classes for my function and was able to get everything working. Thanks for pointing me in the right direction.

3
  • Hi can you explain why not get noRoute on 404 page?? i have use this code $request = $observer->getEvent()->getControllerAction()->getRequest(); $actionName = $request->getActionName(); Mar 1, 2017 at 14:23
  • but its not getting noRoute for 404 page Mar 1, 2017 at 14:24
  • 2
    Hi @Xenocide8998 it is not working when FPC is enable do you have any idea about this. Apr 11, 2018 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.