首页 > 解决方案 > 在 beforeSave() 和停止 save() 调用上从 CakePHP 3.8 模型返回自定义 422 实体错误的正确方法是什么?

问题描述

我目前正在向基于 Cake 3.8 的 API 添加 422 个 http 验证错误。

对于任务控制器,我有类似的东西:

<?php

class TasksController extends AppController
{
    public function initialize()
    {
        parent::initialize();
    }

    public function add(string $id): void
    {
        $validationErrors = [];

        $task = $this->newEntity($this->request->getData(););

        if ($this->Tasks->save($task)) {
            // Errors added to entity in before save will not cause
            // save() to return false and stop the proccess from
            // making it here
            $this->response = $this->response->withStatus(200);
        } else {
            $validationErrors = [$task->getErrors()];
            if (count($validationErrors) > 0) {
                $this->response = $this->response->withStatus(422);
            } else {
                throw new BadRequestException("The posted entity is is invalid.");
            }
        }

        // Render json output for success / errors
        $this->set($this->createViewVars(['entity' => $task], $validationErrors));
    }
}

对于 TasksTable 我有类似的东西:

<?php

class TasksTable extends AppTable
{
    public function initialize(array $config)
    {
        parent::initialize($config);
    }

    public function beforeSave(Event $event, Entity $task, ArrayObject $options)
    {
        parent::beforeSave($event, $task, $options);

        $task->setError('technician', 'No default technician was able to be found');

        if(count($task->getErrors()) > 0) {
            $event->stopPropagation();
        }

    }
}

在 beforeSave 和 beforeMarshal 上编译数据的某些进程可能会检测到添加请求与系统配置不兼容的问题,这些进程需要抛出验证错误。

第1部分:

上表中的当前代码能够在表的 beforeSave 方法中捕获错误并使用 $event->stopPropagation() 停止数据库事务。但是我想知道从表中返回带有错误的未保存任务实体的正确方法是什么?我可以将实体存储到任务模式并使用自定义 getter 来执行此操作,但似乎会有一些内置功能来处理这个?

第2部分:

有没有一种方法可以触发 $this->Tasks->save($task) 在 beforeSave 中失败(返回 false)以及使用 $event->stopPropagation() 停止查询?

提前致谢!

标签: phpcakephpcakephp-3.0

解决方案


推荐阅读