views:

355

answers:

1

How can I localize strings in cakePhp? I havent had any success with the online documentation. Thanks for any help.

+1  A: 

There are a couple of steps:

  1. First, set the locale to be used
  2. Create one or more .po files for that language
  3. Wrap all of your l10n-able strings with the __() or __d() helper methods

Here's an excerpt from one of my projects:

# app/app_controller.php
uses ( 'L10n' );

class AppController extends Controller {
  public function beforeFilter() {
    /**
     * Derive the desired locale by reading the subdomain from
     * the HTTP_HOST server variable. Locale subdomains can use
     * either the 2 or 3 character ISO code. Information on locale
     * ISO codes is at http://www.loc.gov/standards/iso639-2/php/code_list.php.
     */
    $this->L10n = new L10n();

    /** Auto-detect the request language settings */
    $this->L10n->get();

    /**
     * Set the default "domain" for translations. The domain is the
     * same as the po file name in a given locale directory. e.g.
     * __d( 'homepage', 'message_id' ) would look for the
     * message_id key in homepage.po. Using the __() convenience
     * function will always look in default.po.
     */
    $this->set( 'domain', 'default' );
  }

  # The rest of your AppController code
}

That snippet will set the language. All you need to do is provide the appropriate .po files in the /app/locale/eng/LC_MESSAGES/ directory. The CakePHP book provides sufficient information on this, I think.

If you choose to use just one .po file, you'll wrap your strings with the __() helper. I chose multiple .po files in order to avoid one massive file, so I used the __d() helper so that I could specify which domain (domain == name of the .po file without the .po extension).

UPDATE

I should add that you'll need to use the Translate behavior to help you with database content that requires translation.

Rob Wilkerson
You do not need to instantiate the `L10n` class at all. This happens automatically the first time the `__()` function is invoked.
deceze
Interesting. I did not know that, but since I'm using it here to `get()` the language, wouldn't I need an instance before any `__()` is evaluated?
Rob Wilkerson
No, this is all being done when you invoke `__()`. You can try by baking a new Cake app and just add a single `__('Test')` somewhere, provide a translation .po file for the string and switch your browsers preferred language setting. It'll switch languages without you needing to do anything more.
deceze
There is no way how to change default "domain", __() always uses default domain.
sstevko