Magento 2 - Can you replace any observer with plugin?
-
15-04-2021 - |
题
I am using a observer for the event sales_order_place_before.
It does not work as expected, so I try to replace it with a plugin to see if it does make a difference.
The event sales_order_place_before is dispatched here:
vendor\magento\module-sales\Model\Order.php
public function place()
{
$this->_eventManager->dispatch('sales_order_place_before', ['order' => $this]);
$this->_placePayment();
$this->_eventManager->dispatch('sales_order_place_after', ['order' => $this]);
return $this;
}
As you can see the parameter "order" is passed to the observer.
How can I access the order parameter from a plugin? Is it even possible?
I tried the code from @Amit Bera:
public function beforePlace(\Magento\Sales\Model\Order $order)
{
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/zend_debug.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info("Hello from beforePlace plugin!");
$logger->info("Order ID:");
$logger->info($order->getId());
}
Output:
> 1: Hello from beforePlace plugin!
> 2: Order ID:
> 3:
Line 3 is empty
解决方案
Try the following way:
di.xml
<type name="Magento\Sales\Model\Service\OrderService">
<plugin name="orderservice_place_order_plugin" type="VendorName\ModuleName\Plugin\OrderService"/>
</type>
app/code/VendorName/ModuleName/Plugin/OrderService.php
public function afterPlace(
\Magento\Sales\Model\Service\OrderService $subject,
$result
) {
return $result;
}
其他提示
You can get order object to after, before,around Plugin.
If you check plugin concept the then you can see the first param of the plugin obviously current class/interface object, So you can get order info easily on plugin like event & observer
Let me explain, Suppose, you have defined before plugin on place() function
then before the plugin look like
public function beforePlace(\Magento\Sales\Model\Order $subject)
{
$order = $subject;
...
}
For your case, place()
method does not call that why sales_order_place_before
event does not fire.