CakePHP REST API基本路由



我试图让一个简单的rest API在CakePHP中工作,但由于某些原因,资源路由无法工作。

从一个干净的应用程序(my_app(和蛋糕文档中的简单rest示例开始,执行以下操作:

  1. 在routes.php底部添加了setExtensions和资源
Router::scope('/', function ($routes) {
$routes->setExtensions(['json']);
$routes->resources('Recipes');
});

创建RecipesController:

<?php
namespace my_appController;
use my_appControllerAppController;
class RecipesController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
public function index()
{
echo 'index'; exit;
}
public function view($id)
{
echo "view $id"; exit;
}
public function add()
{
echo 'add'; exit;
}
public function edit($id)
{
echo "edit $id"; exit;
}
public function delete($id)
{
echo "delete $id"; exit;
}
}
  1. 做了一些卷曲请求:
curl -X "POST" -H "Accept: application/json" 'https://nvl.crazytje.com/comapi/Recipes'
=> expecting: "add"
=> result: "index"
curl -X "DELETE" -H "Accept: application/json" 'https://nvl.crazytje.com/comapi/Recipes/1'
=> expecting "delete 1"
=> result: "action not found"
curl -X "GET" -H "Accept: application/json" 'https://nvl.crazytje.com/comapi/Recipes/1'
=> expecting: "view 1"
=> result: action not found
curl -X "PUT" -H "Accept: application/json" 'https://nvl.crazytje.com/comapi/Recipes/1'
=> expecting: "edit 1"
=> result: action not found

我错过了哪些步骤来实现这一点?在过去(几年前(,我一直在做这项工作,不知道我做了什么不同的

不知道这是否是最好的方法,但似乎适用于我的小型应用程序。创建了一个中间件来更改动作

use CakeHttpResponse;
use CakeHttpServerRequest;
class RESTMiddleware {
public function __invoke(ServerRequest $request, Response $response, $next) {
$params = (array)$request->getAttribute('params', []);
if(empty($params['action']) || !method_exists("ComapiControllerInvoiceController", $params['action'])) {
switch(strtolower($request->getMethod())) {
case 'get':
if(empty($params['action']) || $params['action'] == 'index') {
$params['action'] = 'index';
} else {
$params['pass'][] = $params['action'];
$params['action'] = 'view';
}
break;
case 'post':
$params['action'] = 'add';
break;
case 'put':
case 'patch':
$params['pass'][] = $params['action'];
$params['action'] = 'edit';
break;
case 'delete':
$params['pass'][] = $params['action'];            
$params['action'] = 'delete';
break;            
}
}
$request = $request->withAttribute('params', $params);
$response = $next($request, $response);
return $response;
}
}

最新更新