Skip to main content
2 of 3
added 13 characters in body
Amit Bera
  • 77.7k
  • 20
  • 124
  • 239

In my option, it is the best idea to a create Class on Model and also define a Method.

After that, you have to call that method on your observer classes.

Model Class:

 namespace {Vendor}\{ModuleName}\Model;
 class {MyClass}
 {
  public function myFunction()
  {
   // do whatever you need
  }
}

After that called myFunction() on MyObserver using injection.

<?php
namespace {NameSpace};

class MyObserver implements \Magento\Framework\Event\ObserverInterface
{

    private $MyClass;

    /**
     * Constructor
     *
     * @param \{Vendor}\{ModuleName}\Model\{MyClass} $eavSetupFactory
     */
    public function __construct(\{Vendor}\{ModuleName}\Model\{MyClass} $MYClass)
    {
        $this->MyClass = $MYClass;
   }    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $this->MyClass->myFunction();
    }
}
    
Amit Bera
  • 77.7k
  • 20
  • 124
  • 239