CakePHP 3:访问​​模型中的当前用户

zie*_*wit 3 authentication logging cakephp audit-logging cakephp-3.0

因为我是 CakePHP 的新手,所以我有一些无法弄清楚的简单问题。

我使用 CakePHP 3.4。我尝试编写一个简单的记录器功能。应用于记录的每个更改,我都希望记录到 ChangeLog 模型中。

使用 afterSave() 事件,我有以下代码:

public function afterSave($event, $entity, $options) {
  $logTable = TableRegistry::get('ChangeLogs');
  foreach ($entity->getDirty() as $key) {
    if($key != 'modified') {
      $record = $logTable->newEntity();
      $record->previous_value = $entity->getOriginal($key);
      $record->new_value = $entity[$key];
      $record->table_name = 'Stars';
      $record->column_name = $key;
      $record->row_id = $entity->id;
      $record->user_id = [what should i put here?]
      $record->user_id = $_SESSION['Auth']['user']['id'];
      $logTable->save($record);
    }
  }
Run Code Online (Sandbox Code Playgroud)

它运行良好,但我也想知道是哪个用户执行了操作,我不知道如何在模型中获取当前用户。

我尽量避免在控制器中传递参数,因为我希望自动检测用户,并且作为开发人员,我不想每次尝试在控制器中更改/添加新功能时都记住它。

ndm*_*ndm 5

不要直接在 CakePHP 中摆弄超全局变量,这肯定会在某些时候咬你,尤其是在测试环境中!始终使用抽象方法(如会话对象)来访问此类数据!

话虽如此,您可以使用事件将当前用户注入模型回调/事件流。例如全局注册到Model.afterSave,并将当前用户传递到选项中。

这里有一个基本的例子来演示这个原理。想象一下在你的应用控制器中有这样的事情:

use Cake\Datasource\EntityInterface;
use Cake\Event\Event;
use Cake\Event\EventManager;

// ...

public function initialize()
{
    parent::initialize();

    // ...

    EventManager::instance()->on(
        'Model.afterSave',
        ['priority' => -1],
        function (Event $event, EntityInterface $entity, \ArrayObject $options) {
            // retrieve the user id from the auth component
            $options['user_id'] = $this->Auth->user('id');
        }
    );
}
Run Code Online (Sandbox Code Playgroud)

给定的优先级-1(默认优先级是10),它将在该事件的模型回调之前被调用,以便在您的表类中您可以user_id通过$options参数访问。

$record->user_id = $options['user_id'];
Run Code Online (Sandbox Code Playgroud)

对于更可重用的东西,您可能会使用自定义侦听器类。还可以查看诸如Auth.afterIdentifyModel.initialize和 之类的事件Controller.intialize/startup,这些事件可以用于注册您的模型事件侦听器并检索当前用户。

也可以看看