CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

i18n routes with CakePHP 1.3

Internationalizing a CakePHP application can be tricky when it comes to deal with i18n urls. We will see in this article how the Custom route classes introduced by CakePHP 1.3 could be used to add the current language to your urls in a few lines of code.

EDIT: This proof of concept has now been improved and a better version of the code below can be found in CakeDC's I18n plugin on Github

Requirements

This article will not go too deep in internationalizing an application as many resources already exist about it. We suppose the following:

  • Your application defines the current language on given the language code passed in the url
  • The available languages are configured via Configure::write('Config.languages', array('eng', 'fre', 'deu'));
  • You use the CakePHP array syntax for defining urls:
    • $this->Html->link('link', array('controller' => 'posts', 'action' => 'view', $post['Post']['id']));
    • $this->redirect(array('controller' => 'posts', 'action' => 'index'));
    • Router::url(array('controller' => 'posts', 'action' => 'index'), true);

Custom routes were already introduced by Mark Story on his blog, so we will not do it again here... before continuing be sure you have read "Using custom Route classes in CakePHP"

Show me some code!

I18nRoute

As I said (or not), routes are probably the best place for customizing your urls and add information in them... much more better at least than overriding the Helper::url() method in an AppHelper class!

Custom routes introduced a way to customize how routes are processed in a very easy and powerful way (i.e ~20 lines of code). It is a bit like wrapping the Router class in CakePHP 1.2, a good example of this was the CroogoRouter.

First, we are going to create an I18nRoute class extending CakeRoute in the "/libs/routes/i18n_route.php" file. Here is its code:

<?php
class I18nRoute extends CakeRoute {
/**
 * Constructor for a Route
 * Add a regex condition on the lang param to be sure it matches the available langs
 *
 * @param string $template Template string with parameter placeholders
 * @param array $defaults Array of defaults for the route.
 * @param string $params Array of parameters and additional options for the Route
 * @return void
 * @access public
 */
	public function __construct($template, $defaults = array(), $options = array()) {
		$options = array_merge((array)$options, array(
			'lang' => join('|', Configure::read('Config.languages'))
		));
		parent::__construct($template, $defaults, $options);
	}

/**
 * Attempt to match a url array.  If the url matches the route parameters + settings, then
 * return a generated string url.  If the url doesn't match the route parameters false will be returned.
 * This method handles the reverse routing or conversion of url arrays into string urls.
 *
 * @param array $url An array of parameters to check matching with.
 * @return mixed Either a string url for the parameters if they match or false.
 * @access public
 */
	public function match($url) {
		if (empty($url['lang'])) {
			$url['lang'] = Configure::read('Config.language');
		}
		return parent::match($url);
	}

}

The most important part of the code is in the "match()" method. We just add the current language to the url "lang" named param if it was not set. The constructor was also overriden to add a regex pattern for the "lang" param. Thus, only lang prefixes defined in your list of available languages will be parsed by the route.

Define your routes

It is now time to use this custom route in your application. Here is how the default route for pages could be defined in "/config/routes.php":

App::import('Lib', 'routes/I18nRoute');
Router::connect('/:lang/pages/*', array('controller' => 'pages', 'action' => 'display'), array('routeClass' => 'I18nRoute'));
  1. import the library file containing the custom route
  2. add a ":lang" param in where you want the language code appear in the url
  3. tell the Router you want to use this custom class (third param)

Link from everywhere!

Now you won't have to worry about the language code transmitted in your urls... every generated link will contain the current language code. If you want to switch the language (for instance switching to the French version of your application), you will just have to add the "lang" param to the url array.

Here are some examples of urls which would be generated on the "/eng/posts/index" page:

$this->Html->link(__('French', true), array_merge($this->passedArgs, array('lang' => 'fre'))); // /fre/posts/index
$this->Html->link('link', array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); // /eng/posts/view/2

Disclaimer

This code is experimental and the article shows you how to use CustomRoutes to implement this basic feature. Many improvements could be added to fit your needs (no language code for the default application lang, short languages code...)

Even if the tests we made were successful, we have not used this code in production yet so there may be "real word" use cases that are not handled correctly with this solution... if you find one, please tell us in the comments!

Latest articles

TSL/ SSL Certificates Explained – Why your website should have one

SSL certificates are incredibly important if you want a safe and secure site - especially for end user reassurance. But what are they and why should you be concerned if you do not have one for your website? Confidential information can be exposed to prying eyes, hackers or cyber criminals - SSL certificates offer a line of defense against this. SSL - secure sockets layer) certificates are small data files that are digitally bind a cryptographic key to an organization’s details. When installed on a web server, it activates the padlock and the https protocol. This allows for secure connections between a web server to the browser. They were created to protect sensitive data in transmission. It is designed to provide security while remaining simple enough for everyday use. Typically, these certificates are used to secure credit card transactions, data transfers and logins. The SSL protocol has been traditionally used to encrypt and secure transmitted data. Each time a new and more secure version was released, only the version number changed to reflect the update. However, when the update from SSLv3.0 to the new version was released, the version was renamed to TLSv1.0. Because SSL is still the recognised name, this is what most people refer to when describing these certificates - however, you are actually likely using/getting a TLS certificate. This is important to remember if you get a third party to purchase your certificate and you would like to make sure you are getting the right version/protocol. When secured by TLS, connections have one or more of the following properties:

  • The connection is private/secure because symmetric cryptography is used to encrypt the data transmitted.
  • The identity of the communicating parties can be authenticated using public-key cryptography.
  • The connection ensures integrity because each message transmitted includes a message integrity check using a message authentication code to prevent undetected loss or alteration of the data during transmission.
What is important to also know is that browsers are going to start penalising HTTP sites from 2017. Why? Well because browsers, like Google, want to make it known to their users of sites that may be less secure or do not have a SSL certificate and are collecting sensitive information. From January 2017, Google has started flagging HTTP pages that collect passwords or credit card details as non secure. Ideally, website owners should get onto this as soon as possible and ensure that their sites are secured. Visitors have also started to expect secure sites, research has indicated that they are specifically looking out for a ‘padlock’ or secure notification. This is important to sites in general - not only websites with an online store or login portal. SSL is more than just encrypting data submissions. Have you heard about letsencrypt.org? Let’s Encrypt is a free, automated, and open certificate authority (CA), run for the public’s benefit. It is a service provided by the Internet Security Research Group (ISRG). Letsencrypt.org makes certificates more accessible while guiding you with how to properly set it up.  

Upgrade Cloud9 to PHP7.1 for CakePHP 3.4 compatibility

We've been using https://c9.io for some time to run our training sessions for CakePHP, both the free cakephp training sessions and our standard (paid) cakephp training sessions. The service works great, but they provide a default workspace (Ubuntu 14.04 LTS and PHP 5.5.9) not compatible with the latest version of the CakePHP framework (3.4) requiring PHP 5.6+ (7+ strongly recommended). We wanted to provide an automated upgrade script for legacy cloud9 workspaces to PHP7.1 so we created a gist to upgrade the default workspace here https://gist.github.com/steinkel/4eb1cb0b67ddb92f5d5b04646f470cd5 You can execute this gist using the raw link to the script, for example source <(curl RAW_GIST_URL_HERE) Enjoy!

CakePHP API Plugin

Are you creating an API in CakePHP? This task looks very popular these days, and most of our clients need an API to expose certain services to their own rich client applications, or third party services. Even if it's easy to configure CakePHP to expose a REST API, and there are other plugins that could help you building an API, we found ourselves working on specific tweaks per project to adjust the way the API was designed, so we decided to wrap all these ideas and create a specific CakePHP API Plugin including

  • Services definition
  • Integrated CRUD
  • Nested resources
  • Pagination
  • Sorting
  • Associations
  • Versioning
  • Custom Extensions (data format / transformers)
  • Self documentation
We've gathered all the best practices around API building and CakePHP and wrapped them into an easy to install and setup Plugin to be used as the foundation of your API intensive CakePHP projects. Let's walkthru some of the Plugin features using an example application: the bookmarker tutorial http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html We'll assume you've already created a new CakePHP application and configured it to use the bookmarker database (schema dump here http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html#creating-the-database).

Setting up the CakePHP API Plugin

Download the plugin first composer require cakedc/cakephp-api:dev-master Then ensure plugin is loaded in you bootstrap.php file Plugin::load('CakeDC/Api', ['bootstrap' => true, 'routes' => true]);

Now you have an API!

Test your newly configured "default" API using curl curl -X GET http://bookmarker.dev/api/bookmarks You'll get something similar to: { "status": "success", "data": [], "pagination": { "page": 1, "limit": 20, "pages": 0, "count": 0 }, "links": [ { "name": "self", "href": "http:\/\/bookmarker.dev\/api\/bookmarks", "rel": "\/api\/bookmarks", "method": "GET" }, { "name": "bookmarks:add", "href": "http:\/\/bookmarker.dev\/api\/bookmarks", "rel": "\/api\/bookmarks", "method": "POST" } ] } If you look at the provided output you'll identify we've used a JSend default renderer (status, data) and we append some extra data under 'links' (HATEOAS dynamically generated for your CRUDs) and pagination. The specific "extensions" used can be configured and custom extensions created for your specific needs, see https://github.com/CakeDC/cakephp-api/blob/master/docs/Documentation/extensions.md We'll publish a couple tutorials soon covering some of the features implemented, and explaining how did we use the CakePHP API Plugin to address specific use cases. Meanwhile, please check the documentation here https://github.com/CakeDC/cakephp-api/blob/master/docs/Documentation/overview.md

Giving back to the community

This Plugin's development has been sponsored by the Cake Development Corporation. Contact us if you are interested in:  

BOOK A 15 MINUTES FREE
CONSULTING WITH US:
We Bake with CakePHP