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

Learn more about UX tracking metrics that can help you

With UX being a subjective, human and ever changing experience, it can be seen as difficult to track. However, there are some key tell-tale signs that you should be tracking in order to assess the overall user experience of your website.   Common metrics to use when tracking UX   1. Tracking how long it takes visitors to fill out your forms If your contact forms take too much time to fill in, your visitors or potential clients may get frustrated and fail to complete the form. Forms need to be simple, short and easy. Some tips to keeping forms user friendly and easy to fill in include:

  • keeping the number of fields as simple as possible,
  • Keeping the number of fields to as few as possible, there will be opportunity to ask for more information later on in the customer journey.
  • Testing your form yourself, if you struggle to fill out the fields during testing then you definitely need to relook it!
  • Add a confirmation page or message to let your user know that they have submitted successfully
  2. How many fields are skipped in submitted forms? Do you allow for optional fields in your forms? If you do, do you find a trend on certain fields not being submitted? These fields may be too much trouble for your users to fill in - remember, most visitors are lazy when needing to contact you. Make it as easy as possible but also, its important to ensure that you aren’t being too intrusive when requiring information in your forms. If it’s not ‘need to know’ information, then cut it from your form. These skipped fields give you a good idea as to what your user is thinking and feeling. Make sure to keep an eye on how your forms are submitted and what your users are subconsciously telling you.   3. Analyse your user experience with the use of heat maps Heatmaps give you the best view of the journey your visitors take when visiting your page. From where they are clicking to the amount of engagement a page gets and where. Simple things from users clicking your logo top of page to which links they view as engaging and click through to, these insights help you better optimise your page.      4. Collect feedback from customers and your customer service department Your customer service department is front facing - these are the people that will know what users are saying about your website and they are able to provide insights into where your UX issues. If you haven’t already - this is a great place to start your UX measurement and feedback journey.   If you need an expert to help you with your website, then give CakeDC a call. CakeDC - the experts behind CakePHP.  

Does your website suffer from these challenges? Some tips to fix them!

If you haven’t had a good hard look at your website in a while, now is the time to do so. You will probably find a few things that you’d like fixed. These are the most common challenges that websites fail to fix in time.   Content and technology that is out of date If you had your website built years ago, chances are that it is (severely) out of date. This leaves you vulnerable to security breaches amongst other things. Content is another part of your website that goes out of date, do a spring clean of your overall content and make sure everything listed on your site is still relevant and well organized.   No Call to action for your visitors Are you missing call-to-action triggers such as “Download”, “Contact Us”, “Get started” or “Sign up for free”. You may be losing valuable conversions by not encouraging visitors to engage with your content and brand. This is a quick and easy fix - ideally, you should be checking and updating this type of content regularly to keep abreast of website visitor trends.   Lack of branding It is important as a business owner to make your brand reliable and trustworthy, it is also important to make sure your website correctly displays your clear brand message. Who are you, what do you offer and what tone do you use to project your brand to your clients.   Traffic woes due to SEO troubles If you are not seeing good traffic onto your site, the main culprit may be poor SEO practices. Be sure to regularly check your analytics tracking and if you seeing poor traffic landing on your site then the next port-of-call is to suss out your SEO elements. These include title tags, headlines, content, alt tags, file names, meta descriptions. It is also important to make sure these all align to your key brand message and product offering. The best trick is to select a core group of relevant and related keywords and build your SEO strategy around these.   Websites that haven’t been optimised for mobile If you (or your development team) has failed to quality test the appearance of your site across devices, then you are probably in the majority of companies that are not optimised for mobile. The time is now! Mobile optimised sites are becoming more and more important to business strategy as consumers are no longer bound to only browsing via their computers or laptops. Be sure to check that you are following best practices when optimising for mobile, such as common menu icons and icon placements.   Not sure if your website needs an overhaul? Contact the experts behind CakeDC today to find out more about our development services as well as how we can help you become leaders. CakeDC - We lead, so you can lead.  

Redesigning your website? Do not do this!

From increasing engagement through to increasing overall website performance, there may be aspects of your site that you are currently unhappy with or are looking to improve. Redesigning your website may be necessary due to lack of performance or a brand overhaul, but there are certain things that you should avoid at all costs when redesigning your website.   1. Not considering risk mitigation Most creative or marketing agencies offer web redesigns are part of their packages, however, often fail to outline the different risks that you may face. Such risks include loss of data, server failures, loss of website functionality, bugs and QA testing timelines. To fully understand your risk exposure, it is ideal to consider all individual changes or updates being made and then multiply by the depth of change for each element.   2. An overcrowded home page We understand, when given the opportunity to redesign your website, the first goal is to get all of your messaging across to your potential clients. However, the biggest mistake when doing this, is to inundate the user with too much information and overcrowd your homepage. This leaves visitors confused, overwhelmed - Users make a decision on whether or not to continue browsing after 3 seconds. It is important to ensure that all information is presented in a concise manner. Perhaps investigate infographics to reduce word dense designs.   3. It’s difficult to contact you Leaving out essential contact information or links to your social sites may discourage potential clients from trying to contact you. Keep your information handy in the footer of each page, as well as on its on contact page. The contact page gives you the opportunity to include a contact form as well as other relevant information that may be useful to your visitors.   4. Not having responsive web design and cross device QA testing Your website visitors will become frustrated if they are viewing your site on a device that has not been optimised for - leaving the page lacking user friendliness. Make sure to test a variety of devices and ensure your website has responsive web design.   5. Slow site speed and lack of optimisation Having a slow site can take away any favorable first impressions - make sure to optimise thoroughly when developing your site and ensure site speed is up to scratch.   6. Avoid poor or pixelated imagery Make sure to give proper image files to your development team. Including pixelated or poor imagery onto your site displays lack of professionalism to your visitors or potential clients.   Are you struggling with any of the above website redesign issues? Contact the CakeDC team today and speak to the experts behind CakePHP

We Bake with CakePHP