Hello!
I'm using SoftDelete behavior in model and try to catch "afterDelete" in my other custom behaviour, but i can't. How can i emulate/fire this?
My model and behavior classes:
class MyModel extends \Phalcon\Mvc\Model
{
const STATUS_ACTIVE = 1;
const STATUS_DELETED = 0;
public function initialize()
{
// Configuration
static::setup([
'events' => true,
'notNullValidations' => false,
]);
$this->keepSnapshots(true);
$this->useDynamicUpdate(true);
// Behaviors
$this->addBehavior(new Behavior\SoftDelete([
'field' => 'status',
'value' => static::STATUS_DELETED,
]));
$this->addBehavior(new \MyNamespace\Model\Behavior\MyBehavior());
}
}
class MyBehavior extends \Phalcon\Mvc\Model\Behavior implements \Phalcon\Mvc\Model\BehaviorInterface
{
public function notify($eventType, ModelInterface $model)
{
switch ($eventType) {
case 'afterCreate': /* ... some code ... */ break;
case 'afterUpdate': /* ... some code ... */ break;
case 'afterDelete': /* ... some code ... */ break;
default: /* ... some code ... */ break;
}
return true;
}
}
So, the problem is that when i do $myModel->delete()
i catch afterUpdate
event type in behavior but afterDelete
not triggered at all.
Question: Is there any better and more semantically correct way to catch afterDelete
than use afterUpdate
and check that only status
field was changed and from 1 to 0?
My current code is ugly with this checking-after-delete-event stuff:
<?php
namespace MyNamespace\Model\Behavior;
use Phalcon\Mvc\Model\Behavior;
use Phalcon\Mvc\Model\BehaviorInterface;
use Phalcon\Mvc\ModelInterface;
class Blameable extends Behavior implements BehaviorInterface
{
public function notify($eventType, ModelInterface $model)
{
/* ... some code ... */
$fieldsNew = $model->toArray();
// "Model has not a valid snapshot" exception workaround
try { $fieldsOld = $model->getSnapshotData(); }
catch (\Exception $e) { $fieldsOld = []; }
try { $fieldsChanged = $model->getChangedFields(); }
catch (\Exception $e) { $fieldsChanged = []; }
// Try to detect afterDelete with SoftDelete and set correct event type for logger
if ($model::STATUS_DELETED != $fieldsOld['status'] && in_array('status', $fieldsChanged) && $model->isDeleted())
$eventType = 'afterDelete';
/* ... some code ... */
return true;
}
}