You are implementing customization of the sales management within the module MyCompany_MySalesProcess. You have created several event observers to add the custom functionality. Each observer is a separate class, but they require some common functionality. How do you implement the common functionality in the event observers, keeping maintainability and testability in mind?
A. You create a trait with the common methods and use the trait in the observer classes.
B. You create an abstract class AbstractObserver with the common methods and extend the observer classes from it.
C. You create a regular class implementing the common functionality as public static methods and call those from the observers.
D. You create a regular class implementing the common functionality as public methods and use constructor injection to make them available to the observers.
The correct answer is D.
But what about B?
In the custom module that is developing, I used AbstractObserver class.
Why is it a big mistake?
Case D
..............................................ObserverA.php
namespace Test\Code\Observer; use Test\Code\Model\Custom; class ObserverA implements ObserverInterface { protected $customInstance;
public function __construct( Custom $customInstance ) { $this->customInstance = $customInstance; }
public function execute(
\Magento\Framework\Event\Observer $observer
)
{
$this->customInstance->getSomeData();
} }
Case B
..............................................ObserverA.php
namespace Test\Code\Observer; use Test\Code\Observer\AbstractObserver; class ObserverA extends AbstractObserver { public function execute(
\Magento\Framework\Event\Observer $observer
)
{ $this->customInstance->getSomeData(); } }
.....................................................AbstractObserver.php
namespace Test\Code\Observer\AbstractObserver; use Test\Code\Model\Custom; abstract class AbstractObserver implements ObserverInterface { protected $customInstance; public function __construct( Custom $customInstance ) { $this->customInstance = $customInstance; } }
B. You create an abstract class AbstractObserver with the common methods and extend the observer classes from it.
Though It is a little bit tricky option. In the documentation, business logic is not allowed in observers even in abstract observers. So for that reason, it is not correct. But if it uses DI it could be correct. I guess.