Search code examples
laraveldesign-patternstraitsextend

Laravel: difference between using a Trait or extending a model


We're working on a Laravel application with a scheduling module. The module has three types of classes that can be put in an agenda: Task, Event and Department. We've therefore come up with the following class diagram: Class Diagram Now, our question: if we were to realise this diagram, should we use a Trait or should we extend a Plannable model.

Plannable model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Plannable extends Model
{
    // Code
}

Task model:

<?php

namespace App;

use App\Plannable;

class Task extends Plannable
{
    // Code
}

Or should we use this as a trait:

Plannable trait:

<?php

namespace App\Traits;

trait Plannable
{
    // Code
}

Task model:

<?php

namespace App;

use App\Plannable;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    use Plannable;
    // Code
}

Solution

  • Extending a parent/abstract class is best used when the models all share common characteristics but behave (function) in a unique way. For instance, Cars and Motorcycles are both Vehicles. They share common characteristics (e.g. headlights, indicators, engines, transmissions, etc.), but how to operate() them is unique from class to class.

    Traits, on the other hand, are better used when the using classes (or Eloquent models in this case) require common functionality (i.e. methods) despite having different characteristics.

    Without knowing more about your project, it seems like you're looking for the latter with each model having common functionality (perhaps addToCalendar(), reschedule(), etc.) despite having different characteristics.