0

I would like to display the result from Observer to every page, any way I can do it?

app/code/MyVendor/GeoIp/Observer/GeoObserver.php

<?php

namespace MyModule\GeoIp\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use MyModule\GeoIp\Helper\GeoLocation;
use Magento\Framework\View\LayoutInterface;

class GeoObserver implements ObserverInterface {

public function __construct(
    GeoLocation $helperGeoLocation,
    LayoutInterface $layout
){
    $this->helpGeoLocation = $helperGeoLocation;
    $this->layout = $layout;
}

public function execute(Observer $observer)
{

    $displaytext = $this->helpGeoLocation->getCountryCodeByIp();

    $result = "<p> GEO: $displaytext </p>";

    return $result;
}

}
1
  • 1
    Why not adding this code directly into a block rather than an observer ? And then just call the block to everypage ?
    – Claims
    Dec 6, 2022 at 15:50

1 Answer 1

0
Create event : events.xml (app/code/VendorName/ModuleName/etc/frontend/events.xml)
code:
<event name="controller_action_predispatch">
    <observer name="page_observer" instance="Vendor\Module\Observer\allPage" />
</event>

Create the class file with name allPage.php app/code/VendorName/ModuleName/Observer/allPage.php

<?php
namespace VendorName\ModuleName\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;

class allPage implements ObserverInterface
{
    public function execute(Observer $observer)
    {
       //Your Code
    }
}

This code will execute for all frontend pages.
1
  • Thank you for your ans, but any way to return it to a custom block?
    – hill2011
    Dec 6, 2022 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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