What is the Laravel trait pattern? What is the Laravel trait pattern? laravel laravel

What is the Laravel trait pattern?


Traits, being introduced with PHP 5.4, in general solving one big problem of PHP: single inheritance. A rough guess from me: if PHP would support multi inheritance (inherit from more than one class) there wouldn't be traits.

Nevertheless, traits are a good thing to reduce duplications of code and furthermore provide same fuctionality to multiple classes.

  • As far as I can see, there is no real (pattern) name for using traits.
  • It is not a pattern per se, as compared to other Software design pattern, just call it traits ;)
  • Laravel and maybe more specifically the Cashier package are good examples of using traits. If somebody finds other good examples please mention it.
  • Traits can be extended by other traits. That of course creates more and more complexity. To extend you probably should consider other methods to bring a functionality to your class. "Chaining" of traits adds load of complexity.


Traits are similar to extending classes, but with a few differences

  • Traits don't have a constructor
  • Classes can only extend one class, but have multiple traits

They're similar to mixins in other languages. I guess you could say its an easy way to use the DRY principle.

Since traits don't have constructors, any dependencies they have would need to exist on the class they're used on. I think depending on the class to have something other than the trait would be a bad design pattern. So you would have to use a service locator to pull in dependencies.

If you would rather not use a service locator, I would recommend using a class rather than a trait. You could have a BarcodeChecker class that you could inject into the constructor of the classes you want to use it. Then instead of $this->checkBarcode() you would use $this->barcodeChecker->check(). I think that would be a better design pattern if the trait requires dependencies.