@@ -27,6 +27,8 @@ protected function init(): void
2727}
2828class Model_Item extends Model
2929{
30+ use ModelSoftDeleteTrait;
31+
3032 public $ table = 'item ' ;
3133
3234 protected function init (): void
@@ -37,15 +39,8 @@ protected function init(): void
3739 $ this ->hasOne ('parent_item_id ' , ['model ' => [self ::class]])
3840 ->addTitle ();
3941
40- $ this ->addField ('is_deleted ' , ['type ' => 'boolean ' , 'nullable ' => false , 'default ' => false ]);
41- $ this ->addCondition ('is_deleted ' , false );
42- $ this ->onHook (Model::HOOK_BEFORE_DELETE , function (Model $ entity ) {
43- $ softDeleteController = new ControllerSoftDelete ();
44- $ softDeleteController ->softDelete ($ entity );
42+ $ this ->initSoftDelete ();
4543
46- $ entity ->hook (Model::HOOK_AFTER_DELETE );
47- $ entity ->breakHook (false ); // this will cancel original Model::delete()
48- });
4944 }
5045}
5146class Model_Item2 extends Model
@@ -81,6 +76,21 @@ protected function init(): void
8176 }
8277}
8378
79+ trait ModelSoftDeleteTrait {
80+ protected function initSoftDelete (): void
81+ {
82+ $ this ->addField ('is_deleted ' , ['type ' => 'boolean ' , 'nullable ' => false , 'default ' => false ]);
83+ $ this ->addCondition ('is_deleted ' , false );
84+ $ this ->onHook (Model::HOOK_BEFORE_DELETE , function (Model $ entity ) {
85+ $ softDeleteController = new ControllerSoftDelete ();
86+ $ softDeleteController ->softDelete ($ entity );
87+
88+ $ entity ->hook (Model::HOOK_AFTER_DELETE );
89+ $ entity ->breakHook (false ); // this will cancel original Model::delete()
90+ });
91+ }
92+ }
93+
8494class ControllerSoftDelete {
8595 protected function init (): void {
8696 // example broken for clone "Object cannot be cloned with hook bound to a different object than this"
0 commit comments