Book Image

CakePHP 2 Application Cookbook

Book Image

CakePHP 2 Application Cookbook

Overview of this book

Table of Contents (20 chapters)
CakePHP 2 Application Cookbook
Credits
Foreword
About the Authors
About the Reviewer
www.PacktPub.com
Preface
Index

Parsing extensions


It's common for applications to use a file extension as part of the URL. This can sometimes help orientate the user to the type of content found in that location or for your application to easily deal with data types such as JSON or XML.

In this recipe, we'll look at how easy it is to parse extensions using the framework.

Getting ready

For this recipe, we'll use a books controller from previous chapter, which will return a listing of books from the books database table as a JSON response. So, find a file named BooksController.php in app/Controller/.

How to do it...

Perform the following steps:

  1. First, add the following line to your routes.php file located in app/Config/:

    Router::parseExtensions('json');
  2. Then, we'll load the RequestHandler component in our BooksController class using the following code:

    public $components = array('RequestHandler');
  3. We'll also add a listing() method with the following code:

    public function listing() {
      $books = $this->Book->find('all', array...