如何使用CakePHP 3.3存储所有save($data)的所有$data?
我曾经在AppModel::beforeSave($data)(Cake 1.2)中实现了一个小日志代码(将$data转换为json并存储在VARCHAR、username和datetime上)
更新:
我已尝试使用EventListenerInterface:
namespace App\Model\Event;
use Cake\Event\EventListenerInterface;
use Cake\ORM\TableRegistry;
class LogModel implements EventListenerInterface
{
public function implementedEvents()
{
return [
'Model.beforeSave' => 'logSave'
];
}
public function logSave($event, $data = null, $options = null)
{
$eventTable = TableRegistry::get('Event');
$eventEntity = $eventTable->newEntity();
$eventEntity->event = json_encode($event);
$eventEntity->data = json_encode($data);
$eventEntity->className = get_class($event->__get('subject'));
//var_dump($eventEntity->className);exit();
$eventTable->save($eventEntity);
}
}
独自创立php:
//event global
use Cake\Event\EventManager;
use App\Model\Event\LogModel;
$logModel = new LogModel();
EventManager::instance()->on($logModel);
但这导致了无限的递归调用,因为我需要保存(记录)所有保存的数据。有没有办法避免这种情况?
CakePHP 3没有超级模型类的概念。让它成为一种行为并在需要的地方使用它是合适的。
请参阅本节:创建行为
namespace App\Model\Behavior;
use Cake\Datasource\EntityInterface;
use Cake\Event\Event;
use Cake\ORM\Behavior;
use Cake\ORM\Entity;
use Cake\ORM\Query;
use Cake\Utility\Inflector;
class JsonifyBehavior extends Behavior
{
public function jsonify(Entity $entity)
{
/* Your logic */
}
public function beforeSave(Event $event, EntityInterface $entity)
{
$this->jsonify($entity);
}
}
并在各自的表中,调用初始化方法中的行为:
public function initialize(array $config)
{
$this->addBehavior('Jsonify');
}