alnouirah's avatar

Composer override vs trait

Hi Guys.

When we want to override a function that is inside a vendor folder, which way is better to do :

  • use composer override
  • use traits.

what are the cases that you prefer the first option and the cases you go with the other!

0 likes
4 replies
tykus's avatar

What is composer override?

And there is not enough context to answer anyway!

alnouirah's avatar

@tykus

In composer.json, under ["autoload"]["psr-4"], you can add an entry with namespace as the key and path as the value:

{
     "autoload": {

         "psr-4": {

             "BuggyVendor\Namespace\": "myfixes/BuggyVendor/Namespace"
         }
     }
}
alnouirah's avatar

I will explain in detail the case I came across : I'm using spatie translation package. inside HasTranslation trait that I'm using in my models there is a line that calls asJson($value) method. this method accepts a value and returns it as a JSON :

return json_encode($value)

in some cases we need to pass another argument JSON_UNESCAPED_UNICODE which handles languages other than English :

return json_encode($value,JSON_UNESCAPED_UNICODE)

so what is the right way to implement this ! is it to use composer override or to create a trait that overrides this method and use it inside every model that uses HasTranslation trait.

tykus's avatar
tykus
Best Answer
Level 104

@alnouirah you can implement the asJson method yourself in the Model class which will override the trait's asJson method; or write a separate trait to implement asJson as you wish, then collision-resolve in the Model(s):

use HasTranslation, MyHasTranslation {
    MyHasTranslation::asJson insteadof HasTranslation;
}
1 like

Please or to participate in this conversation.