gpt4 book ai didi

authentication - CakePHP 3 : Accessing current user in model

转载 作者:行者123 更新时间:2023-12-04 01:46:46 25 4
gpt4 key购买 nike

由于我是 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);
}
}

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

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

最佳答案

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

也就是说,您可以使用事件将当前用户注入(inject)模型回调/事件流。例如全局注册到 Model.afterSave,并将当前用户传递到选项中。

这里有一个基本的例子来说明原理。在您的应用程序 Controller 中想象这样的事情:

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');
}
);
}

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

$record->user_id = $options['user_id'];

对于更可重用的东西,您可能会使用自定义监听器类。还要检查 Auth.afterIdentifyModel.initializeController.intialize/startup 等事件,这些事件可以用来注册您的模型事件监听器并检索当前用户。

另见

关于authentication - CakePHP 3 : Accessing current user in model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43167001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com