Magento2 Event Observer – Run Function on Every Page

controllersevent-observermagento2

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?

Best Answer

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.

Related Topic