CakePHP:创建跟踪日志以将更改存储在特定表中

时间:2019-07-24 13:31:42

标签: php logging cakephp

我正在尝试为特定表中的更改创建跟踪日志。所以我创建了这个GlobalComponent

<?php 

namespace App\Controller\Component;

use Cake\Controller\Component;

use Cake\ORM\TableRegistry;

class GlobalComponent extends Component
{
    public function traceLog($table, $action, $new_val, $old_val, $user)
    {

        $tl = TableRegistry::get('TraceLog')->newEntity();
        $tl->table_name = $table;
        $tl->action_type = $action;
        $tl->new_val = $new_val;
        $tl->old_val = $old_val;
        $tl->user_id = $user;
        $tl->created = date("Y-m-d H:i:s");

        TableRegistry::get('TraceLog')->save($tl);
    }
}

在保存add之后的Transaction方法中,我这样调用该方法:

//TraceLog add action

$transaction_array = $transaction->toArray();
foreach ($transaction_array as $propName => $propValue) { 
     $new_val .= $propName.': '.$propValue.', ';
}
$this->Global->traceLog('Transactions', 'create', $new_val, null, $this->Auth->user('id'));

$transaction具有与Users表相似的关联。如何将$proValue用作用户的username而不是id的用户?

又如何在edit方法中获取脏字段并遍历它们以仅存储脏字段?并从中获得旧价值吗?使用相同的方式:

//TraceLog edit action

$transaction_dirty_array = $transaction->method_to_get_only_dirty_fields();
foreach ($transaction_dirty_array as $propName => $propValue) { 
     $new_val .= $propName.': '.$propValue.', ';
     $old_val .= $propName.': '.$get_old_value.', ';
}
$this->Global->traceLog('Transactions', 'edit', $new_val, $old_val, $this->Auth->user('id'));

0 个答案:

没有答案