i18nactiverecord An ActiveRecord that provides internationalization features.

  1. Requirements
  2. Usage
  3. Resources

The i18nActiveRecord is a type of Yii CActiveRecord that provides internationalization features.

It extends the CActiveRecord class by providing an integrated translation capability. The i18nActiveRecord helps to separate text data from other data by keeping several separate translations for the text data.

Requirements

Tested with Yii 1.1.10 (Should work with other versions). This page discusses other requirements.

Usage

The schema below can be used to create an Item AR . ~~~ [sql] create table item( id integer not null primary key auto_increment, price double(10,2) not null, name varchar(128) not null, description text ); ~~~ Let’s try to internationalize it. ~~~ [sql] create table item( id integer not null primary key auto_increment, price integer not null );

create table item_i18n( i18n_id integer not null, locale varchar(4) not null, name varchar(128) not null, description text, primary key(i18n_id,locale) ); ~~~

The code below shows the minimal implementation of the AR classes.

class Item extends i18nActiveRecord{
 
}
 
class ItemI18n extends CActiveRecord{
    /**
    * @return string the associated database table name
    */
    public function tableName(){
        return '{{item_i18n}}';
    }
    /**
    *@return array primary key column
    */
    public function primaryKey(){
        return array('i18n_id','locale');
    }
}

Let's see some basic usage of the i18nActiveRecord.

$item = new Item();
$item->price = 2.99;

// add an English translation
$item->setLocale('en_US');
$item->name ='Microwave oven';

// add a French translation
$item->setLocale('fr_FR');
$item->name ='Four micro-ondes';

// save the item and its translations
$item->save();

// retrieve text and non-text translations directly from the main object
echo $item->price; // 12.99
$item->setLocale('en_US');
echo $item->name; // Microwave oven
$item->setLocale('fr_FR');
echo $item->name; // Four micro-ondes

$item->eachTranslation(function($itemi18n){
    //both english and french translation will get new name
    $itemi18n->name= "New name";
});

$item = Item::model()->findByPk(1);
// remove the French translation
$item->removeTranslation('fr_FR');

$items = Item::model()->findAll(); // one query to retrieve all items
$locale = 'en_US';
foreach ($items as $item) {
  echo $item->price;
  $item->setLocale($locale);
  echo $item->name; // one query to retrieve the English translation
}

$items = Item::model()
  ->withI18n('en_US')
  ->findAll(); // one query to retrieve both all items and their translations
foreach ($items as $item) {
  echo $item->price;
  echo $item->name; // no additional query
}

Resources

1 0
8 followers
433 downloads
Yii Version: 1.1
License: BSD-2-Clause
Category: Database
Developed by: rontiki
Created on: Oct 6, 2012
Last updated: 10 years ago

Downloads

show all

Related Extensions