CakePHP 3 - 在某些端点上添加用于常见条件的中间件

时间:2016-10-13 09:05:17

标签: php cakephp

我是CakePHP 3的新手,我想知道如何实现这一目标。基本上我有一个UsersController。该控制器有一些基本的RESTful方法,每个方法都会在继续之前检查有效的请求方法。

例如

class UsersController extends AppController
{

    public function create()
    {
        if ($this->request->is('post') === false) {
            throw new BadRequestException('This API endpoint only accepts a POST request');
            return false;
        }

        if (empty($this->request->data) || !count($this->request->data)) {
            throw new BadRequestException('No POST data received');
            return false;
        }
    }

    public function update()
    {
        if ($this->request->is('post') === false) {
            throw new BadRequestException('This API endpoint only accepts a POST request');
            return false;
        }

        if (empty($this->request->data) || !count($this->request->data)) {
            throw new BadRequestException('No POST data received');
            return false;
        }
    }

    public function delete()
    {
        if ($this->request->is('post') === false) {
            throw new BadRequestException('This API endpoint only accepts a POST request');
            return false;
        }

        if (empty($this->request->data) || !count($this->request->data)) {
            throw new BadRequestException('No POST data received');
            return false;
        }
    }
}

这看起来相当重复,我想我可以构建一个中间件,只对这些方法进行所有请求验证(即如果我有index(),则中间件不适用);但我不确定如何做到这一点。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用Controller Initialize功能来执行常见错误

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

    if (!$this->request->is('post')) {
        throw new BadRequestException('This API endpoint only accepts a POST request');
        return false;
    }

    if (empty($this->request->data) || !count($this->request->data)) {
        throw new BadRequestException('No POST data received');
        return false;
    }

}

您也可以通过方法明确指定 $ this-> request-> params ['action'] ,如

if (!$this->request->is('post') && in_array($this->request->params['action'], ['index','add','delete'])) {
        throw new BadRequestException('This API endpoint only accepts a POST request');
        return false;
    }

希望它能帮到你