Implementing Traits via Behaviors

I just wrote a behavior and would like to implement some traits with it, too.

class TagBaseBehavior extends ModelBehavior
{
    use SoftDeleteFilterTrait;
    use Validation;
    use SoftDelete;
    [...]
}

While my own SoftDeleteFilterTrait was implemented correctly, the others didn’t work. For example validation is easy to test and didnt work anymore.

But if I checkout this post, I see that this is the right way to do it:

What’s the problem with my solution?

Traits and Behaviors are different, so including a trait inside a behavior won’t work out of the box. You’d need to copy the logic in to a behavior from that trait and adapt it to the different lifecycle. The documentation covers this.

Traits are better for performance, so if you can use them, it is best.

1 Like