I am new to CakePHP and in my Cake application I’am trying to integrate an API with versions (V1, V2 etc.). Is the routing in my config/routes.php with nested prefixes the correct way to implement versioning or should I use scopes?
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
$builder->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
//$builder->connect('/', ['controller' => 'Pages', 'action' => 'display', 'homeobsolet']);
$builder->connect('/', ['controller' => 'Start', 'action' => 'index']);
// Admin
$builder->prefix('Admin', function (RouteBuilder $builder) {
$builder->connect('/', ['controller' => 'Users', 'action' => 'index']);
$builder->fallbacks(DashedRoute::class);
});
// topics benennen, Bsp. /tagged/haushalt/garten
$builder->scope('/ksentences', function (RouteBuilder $builder) {
$builder->connect('/tagged/*',
['controller' => 'Ksentences', 'action' => 'topics']);
});
// count topics
$builder->scope('/ksentences', function (RouteBuilder $builder) {
$builder->connect('/hastopic/tag',
['controller' => 'Ksentences', 'action' => 'topicstats']);
});
$builder->fallbacks();
});
/*
* If you need a different set of middleware or none at all,
* open new scope and define routes there.
*/
$routes->prefix('Api', ['path' => '/api'], function (RouteBuilder $builder) {
//No $builder->applyMiddleware() here.
//Parse specified extensions from URLs
$builder->setExtensions(['json']);
$builder->connect('/ksentlist/{diff}',
['controller' => 'Ksentences',
'action' => 'ksentlist',
//'prefix' => 'Api',
],[
'pass' => ['diff']
]
);
$builder->connect('/ksentcount/{diff}',
['controller' => 'Ksentences',
'action' => 'ksentcount',
//'prefix' => 'Api',
],[
'pass' => ['diff']
]
);
$builder->connect('/testapi',
['controller' => 'Ksentences',
'action' => 'testapi',
//'prefix' => 'Api',
]
);
$builder->prefix('V1', ['path' => '/v1'], function (RouteBuilder $routeBuilder) {
$routeBuilder->setExtensions(['json']);
$routeBuilder->connect('/ksentlist/{diff}',
['controller' => 'Ksentences',
'action' => 'ksentlist',
//'prefix' => 'V1',
],[
'pass' => ['diff']
]
);
$routeBuilder->connect('/ksentcount/{diff}',
['controller' => 'Ksentences',
'action' => 'ksentcount',
//'prefix' => 'V1',
],[
'pass' => ['diff']
]
);
$routeBuilder->connect('/testapi',
['controller' => 'Ksentences',
'action' => 'testapi',
//'prefix' => 'V1',
]
);
$routeBuilder->fallbacks();
});
$builder->fallbacks(DashedRoute::class);
});
Thanks a lot for your advice!