1

How do you overwrite a trait function from vendor.

Things i did try in the di.xml

<preference for="\Vendor\Module\Traits\Model\ChangeMe"
            type="\Company\Module\Traits\Model\ChangeMe"/>

In my class

namespace \Company\Module\Traits\Model;

class ChangeMe
{
    use \Vendor\Module\Traits\Model\ChangeMe {
        overrideFunction as private traitOverrideFunction;
    }

    public function overrideFunction()
    {
        dd('over here');
    }
}

But it still calls the vendor class

2 Answers 2

1

You forgot to add extends in this file:

class ChangeMe extends \Vendor\Module\Traits\Model\ChangeMe
0

you first need to debug the issue:

  • Check if the module is working
  • Check logs for the error
  • Check the dependency injection class

Next, if everything is working fine. you need to check if there is any other module class already inheriting the Vendor class's preference.

Rewriting by class preference can cause conflicts if multiple classes extend the same original class. To help solve this problem, you can use plugins as well.

Plugins are configured in the di.xml files and are called before, after, or around methods being overridden.

E.g.

<config>
  <type name="Vendor\Module\Traits\Model\ChangeMe">
       <plugin name="inchoo_catalog_product" type="Vendor\Module\Traits\Model\ChangeMe" />
  </type>
</config>

Create class:

<?php
namespace Company\Module\Traits\Model;
 
class ChangeMe
{
    public function beforeSetPrice(\Vendor\Module\Traits\Model\ChangeMe $traitOverrideFunction)
    {
      
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.