CakePHP 4 - 如何创建简单的 REST 概念验证 API?

CakePHP 4 - How do I create a simple proof of concept REST API?

如何获得在 CakePHP 4 中工作的简单概念验证 REST API?

我遵循了 CakePHP 食谱中的指南 here and here

目前我的 routes.php 文件包含以下内容(删除了注释):

<?php

use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;

return static function (RouteBuilder $routes) {        
    $routes->setRouteClass(DashedRoute::class);    
    $routes->scope('/', function (RouteBuilder $builder) {            
        $builder->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);            
        $builder->connect('/pages/*', 'Pages::display');            
        $builder->fallbacks();
    });
    $routes->scope('/', function (RouteBuilder $builder) {
        $builder->setExtensions(['json']);
        $builder->resources('LocateITAPI');
    });
};

我的控制器包含以下代码:

<?php
// src/Controller/LocateITAPIController.php
namespace App\Controller;

use App\Controller\AppController;

class LocateITAPIController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }

    public function index()
    {        
        echo json_encode(utf8_encode("LocateITAPIController::index()"));
    }

    public function view($id)
    {        
        echo json_encode(utf8_encode("LocateITAPIController::view()"));
    }

    public function add()
    {        
        echo json_encode(utf8_encode("LocateITAPIController::add()"));
    }

    public function edit($id)
    {        
        echo json_encode(utf8_encode("LocateITAPIController::edit()"));
    }

    public function delete($id)
    {        
        echo json_encode(utf8_encode("LocateITAPIController::delete()"));
    }

}

我正在尝试使用浏览器访问它:

http://localhost/app/locateitapi.json

我期待看到 JSON 响应,但我看到的是这个错误:

由于 cakephp naming convention,您收到了该错误消息。

方案一:

使用 url 如:http://localhost/app/locate-i-t-a-p-i.json

方案二: 在路由器中添加:

//http://localhost/app/locateitapi.json
$builder->connect('/locateitapi', ['controller' => 'LocateITAPIController', 'action' => 'index']);
$builder->connect('/locateitapi/add', ['controller' => 'LocateITAPIController', 'action' => 'add']);

方案三:

重命名您的控制器 class 如:

class LocateItApiController ...
// http://localhost/app/locate-it-api.json

class LocateitapiController ...
// http://localhost/app/locateitapi.json