Check below code and use as per your requirement.
Create a new class that extends the original class and overrides the constructor.
<?php
namespace Your\Module\Model;
use Magento\Framework\Model\AbstractModel;
class MyModel extends AbstractModel
{
protected $dependency;
public function __construct(
//Inject the original constructors dependency
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
// Add new dependency
\My\Dependency\Class $dependency,
array $data = []
) {
parent::__construct($context, $registry, $data);
// Use the new dependency
$this->dependency = $dependency;
}
}
Define a new preference for your class in a di.xml
file. This file should be located in app/code/Your/Module/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Framework\Model\AbstractModel" type="Your\Module\Model\MyModel" />
</config>
In this example, we have added a new dependency \My\Dependency\Class
to the constructor of the original class Magento\Framework\Model\AbstractModel
and created a new class Your\Module\Model\MyModel
that extends the original class and overrides its constructor.
In the di.xml
file, we have defined a preference for the original class and specified that our new class should be used instead.
UPDATED
Here is an example of how to use override the __construct
property using plugin:
Setp 1 :- Create etc/di.xml
file.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Vendor\Module\Model\YourClass">
<plugin name="your_plugin_name" type="Vendor\Module\Plugin\YourPlugin" sortOrder="1" />
</type>
</config>
Step 2 :- Now Create plugin in this path Plugin\YourPlugin.php
<?php
namespace Vendor\Module\Plugin;
use Closure;
use Vendor\Module\Model\YourClass;
class YourPlugin
{
public function __construct(
// You want to override constructor parameter here
) {
// You want to override constructor parameter here
}
public function aroundYouWantFunction(YourClass $subject, Closure $proceed)
{
// Do something before the original __construct method is called
// ...
// Call the original __construct method
$proceed();
// Do something after the original __construct method is called
// ...
}
}
Let me know if any query.
THANKS.