Magento 2 - It is posible to plug-in into a _construct method?
-
29-09-2020 - |
Question
It is possible?
di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\SalesRule\Block\Adminhtml\Promo\Quote">
<plugin name="Vendor_Module::plugin_new" type="Vendor\Module\Plugin\New" sortOrder="1" disabled="true"/>
</type>
</config>
New.php
namespace Vendor\Module\Plugin;
class New{
public function before_construct(ChildBefore $subject, $interceptedInput)
{
echo '<pre>';
var_dump($subject);
var_dump($interceptedInput);
echo '</pre>';
return ["(before) $interceptedInput (/before)"];
}
}
Solution
No, unfortunately you can't. To overwrite _construct
function, you have to use preference:
<preference for="Magento\SalesRule\Block\Adminhtml\Promo\Quote" type="Vendor\Module\Other\New" />
New.php
namespace Vendor\Module\Other;
class New extends Magento\SalesRule\Block\Adminhtml\Promo\Quote{
protected function _construct()
{
echo '<pre>';
[Your code here]
echo '</pre>';
return parent::_construct();
}
}
OTHER TIPS
No, unfortunately plugins can only be used to to extend the behavior of any public method within a Magento class. Thus, they cannot be used to extend protected/private methods such as the _construct()
method.
In order to modify those protected/private methods you will have to use preferences.
If you want to find out when and when not to use plugins I suggest you have a look at this great post: Rewriting Magento 2 classes vs Plugins
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange