1

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.

2

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:

<?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
   }
}




   // Calling in Controller
   <?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;
}

}

  • If that is form different module, not a single module. like an observer from AAA module and controller from BBB module. how call? – Hansraj Systematix May 21 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. – Milind Singh May 21 at 6:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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