CakePHP Routing File Extension

CakePHP (I’m using 3.x), via the Bake console, provides developers a fast and easy way to stand up an application.  With a small amount of information about your database and executing a few Bake commands, CakePHP can scaffold various MVC classes for you to use in building your application. This post doesn’t detail how to build a CakePHP application — the documentation does an excellent job of that — but rather illustrates how, with a few lines of code, you can enable your routes to return JSON or XML by simply appending the desired extension to your URL.

The CakePHP documentation has two nice tutorials to get you started quickly and showcases some of Cake’s essential tools like the Bake console. The Blog Tutorial will walk you through installing CakePHP, creating a database, and creating enough classes and artifacts to create a small CRUD system. The database instructions create an “articles” table: I’ll refer to that table here to demonstrate enabling the routing file extension capability and showcase how you can return responses to clients in JSON or XML by simply adding the appropriate URL extension (e.g. http://localhost:8765/articles.json).

After the Blog application is Baked load the ‘RequestHandler’ component in your src/ArticlesController.php class or make it available to all your controllers by adding the code to your src/AppController.php:

route-appcontroller

The final step is to enable named extensions in your config/routes.php file:

route-routes

And your done! If you access your articles route without an extension you’ll get your view content returned:

route-articles-1

However when the .json or .xml file extension is added to the URL corresponding to the Articles route (e.g. articles.json) CakePHP will serve the response in the requested format:

route-articles-2

Have a look at the following resources for more information about CakePHP, it’s routing features and REST capabilities:

Leave a comment