0

I have my custom controller that has my custom code, now I need to run that code when any URL hits from the site.

My Controller URL is like

common/index/code run

can anyone help me how can I archive this in Magento ver. 2.3.5-p1

1
  • Easy way is to use ajax on document load Commented Dec 27, 2021 at 8:24

1 Answer 1

1
  1. create events.xml at following location.

app\code\Vendor\Extension\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_custom_observer" instance="Vendor\Extension\Observer\MyClass" shared="false" />
  </event>
</config>
  1. Now create MyClass.php file on following location.

app\code\Vendor\Extension\Observer\MyClass.php

<?php 
namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

class MyClass implements ObserverInterface
{
   public function execute(\Magento\Framework\Event\Observer $observer)
   {
        // THIS EVENT CALL ON EVERY URL
       // insert your custom code here, according to your requirement
   }
}

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.