2

I have created a custom observer below:

Observer file

public function abc($order,$itemIds) {

}

Controller file

public function aaa($order,$itemIds) {
    here we want to call abc($order,$itemIds);
    }

Want to call this observer function in custom controller file. How can do this? Anyone have an idea for that please.

1 Answer 1

3

The observer is a class same as any other class in Magento and can be initialized via Dependency Injection in the constructor or via ObjectManager (not preferred).

For Example:

In your

MyVendor\MyModule\Observer\SaveObserver

<?php
namespace MyVendor\MyModule\Observer;

use Magento\Framework\Event\ObserverInterface;

class SaveObserver implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        try {
            // Do something
        } catch (\Exception $e) {
            // silence
        }
    }

   public function abc($order,$itemIds) {
      // Your public function
   }
}

In your

MyVendor\MyModule\Controller\Adminhtml\Help\Index

<?php

namespace MyVendor\MyModule\Controller\Adminhtml\Help;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use MyVendor\MyModule\Observer\SaveObserver;
/**
 * Class Index
 */
class Index extends Action
{
/**
 * ResultPageFactory
 * @var PageFactory
 */
public $resultPageFactory;

public $observer;

/**
 * Index constructor.
 * @param Context $context
 * @param PageFactory $resultPageFactory
 */
public function __construct(
    Context $context,
    PageFactory $resultPageFactory,
    SaveObserver $observer
) {
    parent::__construct($context);
    $this->resultPageFactory = $resultPageFactory;
    $this->observer = $observer;
}

/**
 * @return \Magento\Backend\Model\View\Result\Page
 */
public function execute()
{
    /** @var \Magento\Backend\Model\View\Result\Page $resultPage */
    $resultPage = $this->resultPageFactory->create();
    $order = null;
    $itemIds = null;

    $this->observer->abc($order, $itemIds);




return $resultPage;
    }
    }
3
  • If that is form different module, not a single module. like an observer from AAA module and controller from BBB module. how call? Commented May 21, 2019 at 5:54
  • 1
    Then too you can call in the same manner via the constructor. Also, make sure the module is added as a dependency in your module.xml. Commented May 21, 2019 at 6:03
  • 1
    This is correct but misleading, for code composition and following the SRP an observer should be calling the logic not containing the logic. Function abc should exist in a third class that both the controller and the observer (the entry points for the logic) call individually. Commented Mar 22, 2022 at 23:06

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.