事实证明这比应该的更难。我想做什么:
Router::connect('/:api/:version/:controller/:action/*',
array(),
array(
'api' => 'api',
'version' => '2.0|2.1'
)
);
让它映射到控制器动作。例如,有这个:
http://example.com/api/2.0/users/get/1
...在用户控制器中映射到此...
public function api_2_0_get()...
我错过了什么?
答案 0 :(得分:2)
您错过了既不支持,也不实际使用前缀路由的事实。您将需要连接每个前缀的路由,例如
Router::connect('/api/2.0/:controller/:action/*',
array(
'prefix' => 'api_2_0',
'api_2_0' => true
)
);
Router::connect('/api/2.1/:controller/:action/*',
array(
'prefix' => 'api_2_1',
'api_2_1' => true
)
);
另请参阅 Cookbook > Development > Routing > Prefix Routing
或使用自定义路由类,从多个路由元素构建动作名称,类似于
应用/路由/路由/ VersionedApiRoute.php 强>
App::uses('CakeRoute', 'Routing/Route');
class VersionedApiRoute extends CakeRoute
{
public function parse($url)
{
$route = parent::parse($url);
if (!$route) {
return false;
}
$route['action'] =
'api_' . str_replace('.', '_', $route['version']) . '_' . $route['action'];
return $route;
}
}
应用/配置/ routes.php文件强>
App::uses('VersionedApiRoute', 'Routing/Route');
Router::connect('/api/:version/:controller/:action/*',
array(),
array(
'routeClass' => 'VersionedApiRoute',
'version' => '2\.0|2\.1' // this is a regex, so don't forget to escape the dots
)
);
另请参阅 Cookbook > Development > Routing > Custom Route Classes