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
About the Authors
About the Reviewer

Handling languages

When building a multi-language application, you may want to allow your users to change the language of the content they're viewing through the URL.

In this recipe, we'll look at how you can use routing to deliver content in different languages.

Getting ready

First, we'll need a controller to work with, so create an ExampleController.php file in app/Controller/ with the following content:

App::uses('AppController', 'Controller');

class ExampleController extends AppController {

We'll then need a view, so create a file named language.ctp in app/View/Example/.

How to do it...

Perform the following steps:

  1. Open the routes.php file in app/Config/ and add the following lines to it:

    Router::connect('/:language/:controller/:action/*', array(), array(
      'language' => '[a-zA-Z]{3}',
      'persist' => array('language')
  2. Open your AppController.php file in app/Controller/ and add the following beforeFilter() method:

    public function beforeFilter() {