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:
Hi @apinard
You’re close.
We don’t support this because maintaining it is extremely difficult. You can write your own implementation; you should do it to make things predictable and the code robust.
Don’t be afraid to duplicate code and ship it with your plugin to gain the flexibility benefits. Something like this:
<?php namespace Acme\MyPlugin\Behaviors;
use System\Classes\ModelBehavior;
/**
* RevisionableModel implementation of \October\Rain\Database\Traits\Revisionable
*
* Usage:
*
…
What’s the problem with my solution?
daft
April 24, 2023, 6:40am
#2
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