rock3t
rock3t

Reputation: 2233

Repeated methods for models

I wrote a handful of models and noticed I have repeated methods - methods which are used across all or majority of models.

What would be the best approach to porting them to another file and adding to model as required?

traits?

Upvotes: 0

Views: 53

Answers (1)

Rehan Manzoor
Rehan Manzoor

Reputation: 2743

IMHO create an abstract class DomainModel, extend this class with Illuminate\Database\Eloquent\Model and finally use these traits inside MyModel

use Illuminate\Database\Eloquent\Model

abstract class DomainModel extends Model
{
    use ModelMethods1, ModelMethods2

}

And then extend DomainModel in your model classe

class User extends DomainModel
{

}

This gives you flexibility.

  1. Extending your Model Classes from either Illuminate\Database\Eloquent\Model or DomainModel.
  2. You can use your trait independantly in any Model Class

I've used this approach in a large scale project and it worked really well.

Upvotes: 1

Related Questions