[英]How to log $data of all save($data) in CakePHP 3?
How do I store all $data of all save($data) using CakePHP 3.3? 如何使用CakePHP 3.3存储所有save($ data)的所有$ data?
I used to implement a small log code (converting the $data to json and storing it on VARCHAR, username and datetime) in the AppModel::beforeSave($data) (Cake 1.2) 我曾经在AppModel :: beforeSave($ data) (Cake 1.2)中实现了一个小的日志代码(将$ data转换为json并将其存储在VARCHAR,用户名和日期时间上)。
Update: 更新:
I've tried use EventListenerInterface: 我试过使用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);
}
}
bootstrap.php: bootstrap.php:
//event global
use Cake\Event\EventManager;
use App\Model\Event\LogModel;
$logModel = new LogModel();
EventManager::instance()->on($logModel);
But this resulted in an infinite recursive calls because I need save (log) the data of all saves. 但这导致了无限递归调用,因为我需要保存(记录)所有保存的数据。 Is there a way to avoid that?
有办法避免这种情况吗?
CakePHP 3 doesn't have the concept of a super model class. CakePHP 3没有超级模型类的概念。 It'd be appropriate to make it a behavior and use it where needed.
使它成为一种行为并在需要时使用它是适当的。
Refer to this section: Creating a Behavior 请参阅本节: 创建行为
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);
}
}
And in your respective table, call the behavior in the initialize method: 并在您各自的表中,调用initialize方法中的行为:
public function initialize(array $config)
{
$this->addBehavior('Jsonify');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.