我希望能够同时支持api中的多个版本化端点,例如:
/api/v1.1/counties/get
/api/v1.2/counties/get但是在试图实现这个路由的过程中,Cake为什么要这样做有点困惑,因为我一直得到一个
错误:找不到控制器类县。
尝试1:
Router::scope('/api', function ($routes) {
$routes->setExtensions(['json']);
$routes->fallbacks('DashedRoute');
$versions = [
1.1
];
foreach ($versions as $version) {
$routes->scope('/' . $version, function($routes) {
$routes->resources('Counties', [
'controller' => 'Counties',
'prefix' => 'api',
'map' => [
'get' => [
'action' => 'get',
]
]
]);
}
}
});企图2:
Router::scope('/api', function($routes) {
$routes->scope('/v1.1', function($routes) {
$routes->resources('Counties', [
'controller' => 'Counties',
'map' => [
'get' => [
'action' => 'get'
]
]
]);
});
$routes->connect(
'/v1.1/counties/get',
[
'controller' => 'Counties',
'action' => 'get',
]
);
});我目前使用的目录结构(仍有待讨论):
src/Controller/Api/V1.1,它将使用src/Controller/Api中的基本控制器,并在需要时用存根方法对它们进行扩展。我的大部分“胖”都在模特身上。
src/Controller/Api/V1.1/CountiesController.php有:
namespace App\Controller\Api\V1.1;
class CountiesController extends AppController
{
}会感谢你的任何见解
发布于 2018-01-26 18:20:31
不能在命名空间(文件夹)结构中像点一样使用字符,因为这是无效的PHP。
您要寻找的是使用前缀路由和path选项,以便连接名称空间中有效的前缀,并为路由提供一个自定义路径(URL段),如下所示:
Router::prefix('api', function (RouteBuilder $routes) {
// ...
$routes->prefix('v11', ['path' => '/v1.1'], function (RouteBuilder $routes) {
$routes->resources('Counties', [
'map' => [
'get' => [
'action' => 'get'
]
]
]);
});
});这将连接以下路由(您可以通过in the shell通过bin/cake routes检查连接的路由):
+---------------------+-----------------------+--------------------------------------------------------------------------------------------------+
| Route name | URI template | Defaults |
+---------------------+-----------------------+--------------------------------------------------------------------------------------------------+
| v11:counties:index | api/v1.1/counties | {"controller":"Counties","action":"index","_method":"GET","prefix":"v11","plugin":null} |
| v11:counties:add | api/v1.1/counties | {"controller":"Counties","action":"add","_method":"POST","prefix":"v11","plugin":null} |
| v11:counties:view | api/v1.1/counties/:id | {"controller":"Counties","action":"view","_method":"GET","prefix":"v11","plugin":null} |
| v11:counties:edit | api/v1.1/counties/:id | {"controller":"Counties","action":"edit","_method":["PUT","PATCH"],"prefix":"v11","plugin":null} |
| v11:counties:delete | api/v1.1/counties/:id | {"controller":"Counties","action":"delete","_method":"DELETE","prefix":"v11","plugin":null} |
| v11:counties:get | api/v1.1/counties/get | {"controller":"Counties","action":"get","_method":"GET","prefix":"v11","plugin":null} |
+---------------------+-----------------------+--------------------------------------------------------------------------------------------------+然后,CountiesController类将在
src/Controller/Api/V11/CountiesController.php名称空间为:
App\Controller\Api\V11另请参阅
https://stackoverflow.com/questions/48466832
复制相似问题