I am developing an application which has a side available to users (the dashboard) and a back-end side (an API). I want the API side to have pages which output JSON. Thanks to Cake this is made easy with a $this->set('_serialize', [...]);
from a controller in combination with a router setting: Router::extensions(['json', 'xml']);
. I use prefix routing to group the API pages.
Question: how can I make only the API pages support the *.json
pages from the extensions router?
Things I tried
Router::extensions(['json', 'xml']);
line in the routes.php main scope makes it work everywhere, obviously.Putting the Router::extensions(['json', 'xml']);
line inside the prefix scope...
Router::prefix('api', function ($routes) {
//...
Router::extensions(['json', 'xml']);
//...
});
...Makes it work everywhere but inside the API prefix.
Putting it in a new scope...
Router::scope('/api', function ($routes) {
$routes->extensions(['json', 'xml']);
});
...Also makes it work everywhere.
Prefixes are scopes too, just with additional functionality (it's basically a shorthand method for scope()
and passing the prefix
option). In fact, every route is scoped, even if not explicitly connected via the scope()
method.
Use the routes builder that is passed to the callback for the prefix()
method, just as shown in the scope()
example in the docs and your question:
Router::prefix('api', function ($routes) {
$routes->extensions(['json']);
// ...
});
And make sure that you do not use Router::extensions(['json', 'xml']);
anywhere.
See also