gpt4 book ai didi

cakephp - 如何在cakephp 4中使用App Model,想在所有模型上执行SAVE查询后调用一个方法

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

想要记录所有模型表的每次保存事件。我在单个模型中使用了 afterSave 方法,即工作正常。

现在我不想在所有 modelTable 中一一添加相同的方法,而是想在单个文件中编写以下方法,默认情况下所有 modelTable 都可以从该文件中运行此方法/函数。

我也对行为进行了尝试,但不完全知道行为如何为此工作。

public function afterSave($event, $entity, $options)
{
$ActionLogs = TableRegistry::get('ActionLogs');
-------
-------
$ActionLogs->save($ActionLogsEntity);
}

最佳答案

没有AppModel从 CakePHP 3 开始不再是基类。

事件

如果您想为所有 模型运行“保存后”逻辑,那么您现在可以使用事件,特别是 Model.afterSaveModel.afterSaveCommit事件。

所以对于 afterSave你可以像这样注册一个事件:

\Cake\Event\EventManager::instance()->on(
'Model.afterSave',
function (
\Cake\Event\EventInterface $event,
\Cake\Datasource\EntityInterface $entity,
\ArrayObject $options
) {
// run your action logging logic here
}
);

为了涵盖整个应用程序,您通常会在应用程序的 Bootstrap 中注册此类事件,特别是在 Application::bootstrap() 中。 src/Application.php 中的方法文件,config/bootstrap.php文件(这对测试环境非常重要!)。

另见

行为

如果您只想将此应用到特定模型,那么行为将是首选工具。您实际上只需要像在表类中那样定义回调:

// in src/Model/Behavior/ActionLogBehavior.php

namespace App\Model\Behavior;

use ArrayObject;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface;
use Cake\ORM\Behavior;

class ActionLogBehavior extends Behavior
{
public function afterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)
{
// run your action logging logic here
}
}

然后您可以通过它们的 initialize() 将行为添加到相应的表类中方法,例如:

public function initialize(array $config): void
{
// ...

$this->addBehavior('ActionLog');
}

另见

关于cakephp - 如何在cakephp 4中使用App Model,想在所有模型上执行SAVE查询后调用一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73332945/

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