Hello Magento Friends,
In today’s blog, I am going to figure out How to Call Controller when hit any URL from the Website in Magento 2?
The controller is a class that is responsible for a specific URL or group of URLs. It receives requests, processes them, and then returns the results. If you have a custom controller with a custom code and you want to call that controller when any URL gets hit from the website. This can be achieved with the help of the below steps.
Steps to Call Controller when hit any URL from Website in Magento 2:
Step 1: Create events.xml at the following location
app\code\Vendor\Extension\etc\events.xml
And add the code as mentioned below
1 2 3 4 5 6 7 8 |
<?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> |
Step 2: Now create the MyClass.php file in the following location
app\code\Vendor\Extension\Observer\MyClass.php
And add the code as follows
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?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 } } |
Conclusion:
Consequently, this way you can Call Controller when hit any URL from Website in Magento 2. If in case of any trouble, share it with me through the comment box. You can also Get Controller of Each Request in Magento 2. Spread the solution with your friends and stay in the know.
Happy Coding!