Home » Internationalization » Translation2 » Manual
Class Summary Translation2
Class Summary Translation2 – Translation2 class
Translation2 class
Class for multilingual applications management
Class Trees for Translation2
- Translation2
| Class | Summary |
|---|---|
| Translation2_Admin | Administration utilities for translation string management |
Introduction
Introduction – Usage of Translation2
What is Translation2?
Translation2 is a class for multilingual applications management. It provides an easy way to retrieve all the strings for a multilingual site from a data source (i.e. db). The API is designed to be clean, simple to use, yet powerful and extensible. A Translation2_Admin class is provided to easily manage translations (add/remove a language, add/remove a string).
The following containers (data source drivers) are provided:
- PEAR::DB
- PEAR::MDB
- PEAR::MDB2
- gettext
- PEAR::DB_DataObject (experimental, used by PEAR:: HTML_Template_Flexy)
- XML
Some decorator classes will help in various tasks. They can be layered/stacked one on top of the other, in any number. This approach should suit everyone's needs. Currently, the following decorators are provided:
- CacheLiteFunction (for fast file-based caching)
- CacheMemory (for memory-based caching)
- DefaultText (to replace empty strings with their keys or a default text)
- ErrorText (to replace empty strings with an "error_text" fallback message)
- Iconv (to switch from/to different encodings)
- Lang (resort to fallback languages for empty strings)
- SpecialChars (replace html entities with their hex codes)
- UTF-8 (convert UTF-8 strings to ISO-8859-1)
Setup
Translation2 can use different storage containers. Have a look in the /docs/examples dir of the package for some example setups (gettext ini files, SQL DDLs, PHP configuration files, etc).
Usage example
This simple example will show how you can instanciate a Translation2 object and use it to retrieve your translated strings from a db, using the MDB2 driver:
<?php
// set the parameters to connect to your db
$dbinfo = array(
'hostspec' => 'host',
'database' => 'dbname',
'phptype' => 'mysql',
'username' => 'user',
'password' => 'pwd'
);
define('TABLE_PREFIX', 'mytable_');
// tell Translation2 about your db-tables structure,
// if it's different from the default one.
// NB: the default db structure is:
//
// Table "langs" (available languages and meta info)
// +----+------+------+----------+------------+
// | ID | name | meta | encoding | error_text |
// +----+------+------+----------+------------+
//
// Table "strings" (translations)
// +----+---------+----+----+----+-----+
// | ID | page_id | en | de | it | ... |
// +----+---------+----+----+----+-----+
// You can have one table per translation, instead
// of one table for all the languages
//
$params = array(
'langs_avail_table' => TABLE_PREFIX.'langs_avail',
'lang_id_col' => 'ID',
'lang_name_col' => 'name',
'lang_meta_col' => 'meta',
'lang_errmsg_col' => 'error_text',
'strings_tables' => array(
'en' => TABLE_PREFIX.'i18n',
'it' => TABLE_PREFIX.'i18n',
'de' => TABLE_PREFIX.'i18n'
),
'string_id_col' => 'ID',
'string_page_id_col' => 'pageID',
'string_text_col' => '%s' //'%s' will be replaced by the lang code
);
$driver = 'MDB2';
require_once 'Translation2.php';
$tr =& Translation2::factory($driver, $dbinfo, $params);
//always check for errors. In this examples, error checking is omitted
//to make the example concise.
if (PEAR::isError($tr)) {
//deal with it
}
// you can set the charset that the database must use, for instance 'utf8'
$tr->setCharset('iso-8859-1');
// set primary language
$tr->setLang('it');
// set the group of strings you want to fetch from
$tr->setPageID('defaultGroup');
// add a Lang decorator to provide a fallback language
$tr =& $tr->getDecorator('Lang');
$tr->setOption('fallbackLang', 'en');
// add another Lang decorator to provide another fallback language,
// in case some strings are not translated in Italian or English
$tr =& $tr->getDecorator('Lang');
$tr->setOption('fallbackLang', 'de');
// fetch the string with the 'test' stringID
echo $tr->get('test');
// fetch a string not translated into Italian (test fallback language)
echo $tr->get('only_english');
// fetch the whole group of strings, without resorting to the fallback lang
// and without any "decoration"
$rawPage = $tr->getRawPage();
print_r($rawPage);
// fetch the whole group of strings, but applying the decorators
$page = $tr->getPage();
print_r($page);
// you can force the lang and the group of the string you're requesting
echo $tr->get('month_01', 'calendar', 'it');
// the same is true for getRawPage() and getPage()
$page = $tr->getPage('calendar', 'de');
print_r($page);
?>
As you can see, the main methods are get(), getPage() and getRawPage(). The full syntax is
<?php
get($stringID, $pageID, $langID);
?>but if you set the pageID and the langID beforehand, you won't need to specify them at each get() invocation.
NB: you have to check for errors at least on the first invocation of one of these methods, since the db connection is only estabilished at this point, so the chances of failures are higher here.
Extracting language info
Now let's see how we can extract some meta info from the db:
<?php
$tr->getLang(); // no langID => get current lang
$tr->getLang('it'); // same as above, if the current lang is Italian
// the first parameter is the lang code,
// with the second parameter you can filter the info you need
$tr->getLang('it', 'error_text');
$tr->getLang('en', 'name');
$tr->getLang('de', 'meta');
$tr->getLang('de', 'encoding');
?>
Using decorators
Translation2 uses decorators to filter/change the retrieved strings. You can have a chain of decorators (filters), and you can also add yours.
<?php
$tr =& Translation2::factory($driver, $dbinfo, $params);
$tr->setLang('en');
$tr->setPageID('calendar');
// add a memory-based cache decorator, to do some basic prefetching and
// reduce the load on the db
$tr = & $tr->getDecorator('CacheMemory');
// add a file-based cache decorator, to cache the query results through pages
$tr =& $tr->getDecorator('CacheLiteFunction');
$tr->setOption('cacheDir', 'cache/');
$tr->setOption('lifeTime', 3600*24);
// add a fallback lang decorator
$tr = & $tr->getDecorator('Lang');
$tr->setOption('fallbackLang', 'it');
// add a special chars decorator to replace special characters with the html entity
$tr = & $tr->getDecorator('SpecialChars');
// control the charset to use
$tr->setOption('charset', 'ISO-8859-2');
// add a UTF-8 decorator to automatically decode UTF-8 strings
$tr = & $tr->getDecorator('UTF8');
// add a default text decorator to deal with empty strings
$tr = & $tr->getDecorator('DefaultText');
// replace the empty string with its stringID
echo $tr->get('emptyString');
// use a custom fallback text
echo $tr->get('emptyString', 'stringGroup', 'en', 'show this default text');
?>
Getting the stringID from a string
The getStringID() method is the reverse of get(). If you want to translate a string to another language, but you don't know the associated stringID, you can retrieve it with this method:
<?php
$tr->setLang('it');
// translate the Italian string "gennaio" into the English "january"
$stringID = $tr->getStringID('gennaio', 'calendar');
echo $translatedString = $tr->get($stringID, 'calendar', 'en');
?>
Parameter substitution
Translation2 can handle parametric strings, and replace them with parameters passed at runtime (they can be numeric or associative arrays).
<?php
// "hello_user" = "hello &&user&&, today is &&weekday&&, &&day&&th &&month&& &&year&&"
$tr->setParams(array(
0 => '',
'user' => 'Joe',
'day' => '15',
'month' => $tr->get('month_01', 'calendar', 'en'),
'year' => '2004',
'weekday' => $tr->get('day_5', 'calendar', 'en')
));
echo $tr->get('hello_user');
// the above line will print "hello Joe, today is Friday, 15th January 2004"
?>
Getting the translations from multiple "pages"
If your site structure is organized in sections, like a header, a body and a footer, you may use those units as "pages" (or groups of translations), and then fetch them one by one:
<?php
$header_trans = $tr->getPage('header');
$body_trans = $tr->getPage('body');
$footer_trans = $tr->getPage('footer');
?>If you want them all in a single result, just merge them into a single array:
<?php
$translations = array_merge(
$tr->getPage('header'),
$tr->getPage('body'),
$tr->getPage('footer')
);
?>
Admin Introduction
Admin Introduction – Usage of Translation2_Admin
What is Translation2_Admin?
Translation2_Admin is a class meant to help with translation management (add/remove a language, add/remove a string).
Setup
Translation2 can use different storage containers. Have a look in the /docs/examples dir of the package for some example setups (gettext ini files, SQL DDLs, PHP configuration files, etc).
Adding a new language
This simple example will show how you can add a new language [addLang()], using the MDB2 driver:
<?php
// set the parameters to connect to your db
$dbinfo = array(
'hostspec' => 'host',
'database' => 'dbname',
'phptype' => 'mysql',
'username' => 'user',
'password' => 'pwd'
);
// tell Translation2 about your db-tables structure,
// if it's different from the default one.
$params = array(
'langs_avail_table' => 'langs_avail',
'lang_id_col' => 'id',
'lang_name_col' => 'name',
'lang_meta_col' => 'meta',
'lang_errmsg_col' => 'error_text',
'lang_encoding_col' => 'encoding',
'strings_tables' => array(
'it' => 'i18n',
'de' => 'i18n'
),
//OR, if you use only one table,
//'strings_default_table' => 'i18n',
'string_id_col' => 'id',
'string_page_id_col' => 'page_id',
'string_page_id_col_length' => 50, // db field size
'string_text_col' => '%s' //'%s' will be replaced by the lang code
);
$driver = 'MDB2';
require_once 'Translation2/Admin.php';
$tr =& Translation2_Admin::factory($driver, $dbinfo, $params);
// set some info about the new lang
$newLang = array(
'lang_id' => 'en',
'table_name' => 'i18n',
'name' => 'english',
'meta' => 'some meta info',
'error_text' => 'not available',
'encoding' => 'iso-8859-1',
);
$tr->addLang($newLang);
?>That's it. If you specified a new table, it will be created, if you used the same table name as the one of your other translations, it will be ALTERed to host the new language too.
Updating a language
This simple example will show how you can update an existing language [updateLang()]:
<?php
// set some info about the new lang
$langData = array(
'lang_id' => 'en',
'table_name' => 'i18n',
'name' => 'English',
'meta' => 'some updated meta info',
'error_text' => 'this text is not available in English',
'encoding' => 'iso-8859-15',
);
$tr->updateLang($langData);
?>
Removing an existing language
If you want to remove all the translated strings and the info for a certain language, all you have to do is
<?php
$tr->removeLang('fr');
?>
removeLang()
can accept a 2nd parameter ($force):
if you want to remove the whole strings table (regardless it being used
for other languages as well), you can do it this way:
<?php
$tr->removeLang('fr', true);
?>Be warned it won't do any check, so you're responsible for what you do ;-)
Adding new translations
Now let's see how we can add() a new translation for a new or an existing string.
<?php
$stringArray = array(
'en' => 'sample',
'it' => 'esempio',
);
// add the English and Italian translations associated to
// the 'smallTest' stringID and to the 'testGroup' pageID
$tr->add('smallTest', 'testGroup', $stringArray);
?>
Remove a translation
You can remove() the translations for a certain stringID:
<?php
$tr->remove('smallTest', 'testGroup');
?>
Containers Overview
Containers Overview – Overview of the different Translation2 containers
Summary
Translation2 supports different storage drivers; this page is meant to highlight the differences among them.
PEAR::DB, PEAR::MDB, PEAR::MDB2
Translation2 can work with any of these database abstraction layers, just pass the appropriate connection options. These three containers are absolutely identical in what they do and in how they work (wrt Translation2, of course).
<?php
// connection options
$dbinfo = array(
'hostspec' => 'host',
'database' => 'dbname',
'phptype' => 'mysql',
'username' => 'user',
'password' => 'pwd'
);
//select the preferred driver
$driver = 'MDB2'; //switch to 'DB' or 'MDB' as needed
require_once 'Translation2.php';
$tr =& Translation2::factory($driver, $dbinfo, $params);
?>If your table definition is different from the default one, you need to
specify it in the
$params
array.
DB_DataObject
The dataobjectsimple container is the natural choice
for those using
DB_DataObject,
as it is tightly tied to the DAO. This storage driver can use all databases supported by
the PEAR::DB
abstraction layer to fetch data.
For this container, you can't specify a custom table definition, since this feature is not supported yet. You must create a table with the following structure:
// meta data etc. not supported
table: translations
id // not null primary key autoincrement..
string_id // translation id
page // indexed varchar eg. (mytemplate.html)
lang // index varchar (eg. en|fr|.....)
translation // the translated value in language lang.
Here's the MySQL query that can be used to create the table:
create table translations (
id int(11) auto_increment not null primary key,
string_id int(11), page varchar(128),
lang varchar(10), translation text
);
alter table translations add index page (page);
alter table translations add index lang (lang);
alter table translations add index string_id (string_id);
then just run the dataobjects createtables script.
Gettext
This is a wrapper around the gettext base functions, and thanks to File_Gettext you can retrieve an entire domain or write to an existing/new domain without calling the command line compiler utility.
The gettext container requires PEAR::File_Gettext and PEAR::I18Nv2 0.9.1 or newer, make sure you have them installed.
The construction parameters are a bit different from the db ones. To make things as simple as possible, the domain definitions and the available language list are read from two INI files.
langs.ini example:
; If one does not specify the source encoding, ISO-8859-1 is assumed
; Beware that gettext can choke on bad encodings!
[en]
name = English
encoding = iso-8859-1
[de]
name = Deutsch
encoding = iso-8859-1
[it]
name = italiano
encoding = iso-8859-1
domains.ini example:
messages = /path/to/locale
2nddomain = /path/to/locale
3rddomain = /path/to/locale
Sample code to use Translation2 with the gettext container:
<?php
require_once 'Translation2.php';
$params = array(
'prefetch' => false,
'langs_avail_file' => 'path/to/langs.ini',
'domains_path_file' => 'path/to/domains.ini',
'default_domain' => 'messages',
//'file_type' => 'po',
);
// Better set prefetch to FALSE for the gettext container, so we don't need
// to read in the whole MO file with File_Gettext on every request.
$tr =& Translation2::factory('gettext', $params);
$tr->setLang('en');
// Note that, if there is no translation available for a string, the gettext
// container will return the string ID! This behaviour emulates native gettext.
echo $tr->get('mystring');
print_r($tr->getPage('3rddomain'));
?>
XML
The XML container requires PEAR::XML_Serializer 0.13.0 or newer, make sure you have it installed.
<?php
$driver = 'XML';
$options = array(
'filename' => 'i18n.xml',
'save_on_shutdown' => true, //set to FALSE to save in real time
);
require_once 'Translation2.php';
$tr =& Translation2::factory($driver, $options);
?>
constructor Translation2::Translation2
constructor Translation2::Translation2() – Constructor
Synopsis
require_once 'Translation2.php';
void constructor Translation2::Translation2 (
string $storageDriver
, mixed $options = ''
, array $params = array()
)
Description
This constructor is deprecated in favour of the factory() method.
Note
This function can not be called statically.
Translation2::factory
Translation2::factory() – Return an instanciated Translation2 object
Synopsis
require_once 'Translation2.php';
void Translation2::factory (
string $storageDriver
, mixed $options = ''
, array $params = array()
)
Description
This is the Translation2 factory
Parameter
-
string
$storageDriver -
Type of the storage driver ('db', 'mdb', 'mdb2', 'gettext', 'dataobjectsimple')
-
mixed
$options -
Additional options for the storage driver (example: if you are using DB as the storage driver, you have to pass the dsn string here)
-
array
$params -
Array of parameters for the adapter class (i.e. you can set here the mappings between your table/field names and the ones used by this class)
Note
This function can not be called statically.
Translation2::get
Translation2::get() – Get translated string
Synopsis
require_once 'Translation2.php';
string Translation2::get (
string $stringID
, string $pageID = TRANSLATION2_DEFAULT_PAGEID
, string $langID
= null
, string $defaultText = ''
)
Description
Fetch the string from the container. If the string is empty and the DefaultText decorator is used, then return the $defaultText.
Parameter
-
string
$stringID
-
string
$pageID
-
string
$langID
-
string
$defaultText -
Text to display when the string is empty. NB: This parameter is only used in the DefaultText decorator
Note
This function can not be called statically.
Translation2::getDecorator
Translation2::getDecorator() – Return an instance of a decorator
Synopsis
require_once 'Translation2.php';
object Decorator& Translation2::getDecorator (
string $decorator
, object [optional] 1
)
Description
This method is used to get a decorator instance. A decorator can be seen as a filter, i.e. something that can change or handle the values of the objects/vars that pass through.
Parameter
-
string
$decorator -
Name of the decorator
-
object
$obj[optional] -
Object to decorate (the default object being $this)
Return value
returns object Reference of a Translation2_Decorator subclass
Note
This function can not be called statically.
Translation2::getLang
Translation2::getLang() – get lang info
Synopsis
require_once 'Translation2.php';
mixed Translation2::getLang (
string $langID
= null
, string $format = 'name'
)
Description
Get some extra information about the language (its full name, the localized error text, ...)
Parameter
-
string
$langID
-
string
$format -
['name', 'meta', 'error_text', 'array']
Return value
returns [string | array], depending on $format
Note
This function can not be called statically.
Translation2::getLangs
Translation2::getLangs() – get langs
Synopsis
require_once 'Translation2.php';
array Translation2::getLangs (
string $format = 'name'
)
Description
Get some extra information about the languages (their full names, the localized error text, their codes...)
Parameter
-
string
$format -
['ids', 'names', 'array']
Note
This function can not be called statically.
Translation2::getPage
Translation2::getPage() – Get an entire group of strings
Synopsis
require_once 'Translation2.php';
array Translation2::getPage (
string $pageID = TRANSLATION2_DEFAULT_PAGEID
, string $langID
= null
)
Description
Same as getRawPage(), but resort to fallback language and replace parameters when needed.
NB: in Translation2 lingo, a "page" is just a logical "group of strings", it doesn't have to be a "phisical" (HTML or whatever) page.
Parameter
-
string
$pageID
-
string
$langID
Note
This function can not be called statically.
Translation2::getRaw
Translation2::getRaw() – Get translated string (as-is)
Synopsis
require_once 'Translation2.php';
string Translation2::getRaw (
string $stringID
, string $pageID = TRANSLATION2_DEFAULT_PAGEID
, string $langID
= null
, string $defaultText = ''
)
Description
Fetch the string from the container. If the string is empty return $defaultText.
Parameter
-
string
$stringID
-
string
$pageID
-
string
$langID
-
string
$defaultText -
Text to display when the string is empty
Note
This function can not be called statically.
Translation2::getRawPage
Translation2::getRawPage() – Get the array of strings in a page
Synopsis
require_once 'Translation2.php';
array Translation2::getRawPage (
string $pageID = TRANSLATION2_DEFAULT_PAGEID
, string $langID
= null
)
Description
Fetch the page (aka 'group of strings') from the container, without applying any formatting and without replacing the parameters.
Parameter
-
string
$pageID
-
string
$langID
Note
This function can not be called statically.
Translation2::getStringID
Translation2::getStringID() – Get the stringID for a given string
Synopsis
require_once 'Translation2.php';
string Translation2::getStringID (
string $string
, mixed $pageID = TRANSLATION2_DEFAULT_PAGEID
)
Description
Get the stringID of the string passed as parameter
Parameter
-
string
$string -
This is NOT the stringID, this is a real string. The method will return its matching stringID.
-
mixed
$pageID
Note
This function can not be called statically.
Translation2::replaceEmptyStringsWithKeys
Translation2::replaceEmptyStringsWithKeys() – Replace the array values with their keys when empty
Synopsis
require_once 'Translation2.php';
array Translation2::replaceEmptyStringsWithKeys (
array $strings
)
Description
Replace the array values with their keys when empty, just like gettext would do.
Parameter
-
array
$stringsarray of strings (e.g. as returned by getPage())
Translation2::setCharset
Translation2::setCharset() – Set the charset used to get/store the translations
Synopsis
require_once 'Translation2.php';
mixed Translation2::setCharset (
string $charset
)
Description
Set the charset that shall be used when retrieving strings. Currently only used by the MDB2 container.
Parameter
-
string
$charsetcharset name to pass to the container (for instance, 'utf8')
Note
This function can not be called statically.
Translation2::setLang
Translation2::setLang() – Set default lang
Synopsis
require_once 'Translation2.php';
void Translation2::setLang (
string $langID
)
Description
Set the language that shall be used when retrieving strings.
Parameter
-
string
$langIDlanguage code (for instance, 'en' or 'it')
Note
This function can not be called statically.
Translation2::setPageID
Translation2::setPageID() – Set default page
Synopsis
require_once 'Translation2.php';
void Translation2::setPageID (
mixed $pageID
= null
, string $langID
)
Description
Set the page (aka 'group of strings') that shall be used when retrieving strings. If you set it, you don't have to state it in each get() call.
Parameter
-
string
$pageID
Note
This function can not be called statically.
Translation2::setParams
Translation2::setParams() – Set parameters for next string
Synopsis
require_once 'Translation2.php';
void Translation2::setParams (
params $params
= null
)
Description
Set the replacement for the parameters in the string(s). Parameter delimiters are customizable.
Parameter
-
array
$params
Note
This function can not be called statically.
Class Summary Translation2_Admin
Class Summary Translation2_Admin – Administration utilities for translation string management
Administration utilities for translation string management
This package is not documented yet.
Class Trees for Translation2_Admin
-
Translation2
- Translation2_Admin
Translation2_Admin Inherited Methods
| Method Name | Summary |
|---|---|
| Constructor Translation2::Translation2() | Constructor (deprecated in favour of factory()) |
| Factory Translation2::factory() | Return a Translation2 instanciated object |
| Translation2::get() | Get translated string |
| Translation2::getDecorator() | Return an instance of a decorator |
| Translation2::getLang() | get language info |
| Translation2::getLangs() | get available languages |
| Translation2::getPage() | Same as getRawPage(), but resort to fallback language and replace parameters when needed |
| Translation2::getRaw() | Get translated string (as-is) |
| Translation2::getRawPage() | Get the array of strings in a page |
| Translation2::setCharset() | Set the correct charset in the database |
| Translation2::setLang() | Set default lang |
| Translation2::setPageID() | Set default page |
| Translation2::setParams() | Set parameters for next string |
| Translation2::getStringID() | Get the stringID for a given string |
Translation2_Admin::addLang
Translation2_Admin::addLang() – Prepare the storage container for a new lang.
Synopsis
require_once 'Admin.php';
mixed Translation2_Admin::addLang (
array $langData
, array $options
)
Description
If the langsAvail table doesn't exist yet, it is created.
Parameter
-
array
$langData -
array(
'lang_id' => 'en',
'table_name' => 'i18n',
'name' => 'english',
'meta' => 'some meta info',
'error_text' => 'not available',
'encoding' => 'iso-8859-1',
);
-
array
$options -
array(
'charset' => 'latin1',
'collation' => 'latin1_bin',
);
Return value
returns true on success, PEAR_Error on failure
Note
This function can not be called statically.
Translation2_Admin::updateLang
Translation2_Admin::updateLang() – Update the language details.
Synopsis
require_once 'Admin.php';
mixed Translation2_Admin::updateLang (
array $langData
)
Description
Update the language details.
Parameter
-
array
$langData -
array(
'lang_id' => 'en',
'table_name' => 'i18n',
'name' => 'english',
'meta' => 'some new meta info',
'error_text' => 'text not available',
'encoding' => 'iso-8859-15',
);
Return value
returns true on success, PEAR_Error on failure
Note
This function can not be called statically.
Translation2_Admin::removeLang
Translation2_Admin::removeLang() – Remove the language from the langsAvail table and drop the strings table.
Synopsis
require_once 'Admin.php';
mixed Translation2_Admin::removeLang (
string $langID
= null
, boolean $force
= false
)
Description
If the strings table holds other languages and $force==FALSE,
then only the lang column is dropped. If $force==TRUE, the whole
table is dropped without any check
Parameter
-
string
$langID -
Code of the language to remove
-
boolean
$force
Return value
returns true on success, PEAR_Error on failure
Note
This function can not be called statically.
Translation2_Admin::add
Translation2_Admin::add() – add a new translation
Synopsis
require_once 'Admin.php';
mixed Translation2_Admin::add (
string $stringID
, string $pageID
= null
, array $stringArray
)
Description
Add a new translated string (or a set of translated strings) for a given
stringID. For instance, to add the English, Spanish and Italian
translations for the stringID 'example', use the following code:
<?php
$stringArray = array(
'en' => 'example',
'es' => 'ejemplo',
'it' => 'esempio',
);
$tr->add('example', 'mypage', $stringArray);
?>
Parameter
-
string
$stringID -
identificator for the string
-
string
$pageID -
destination pageID, i.e. the group of strings where this string belongs to.
-
array
$stringArray -
Associative array with string translations.
Return value
returns true on success, PEAR_Error on failure
Note
This function can not be called statically.
Translation2_Admin::remove
Translation2_Admin::remove() – remove a translated string
Synopsis
require_once 'Admin.php';
mixed Translation2_Admin::remove (
string $stringID
, string $pageID
= null
)
Description
Remove all the translations for the given stringID +
pageID pair.
Parameter
-
string
$stringID
-
string
$pageID
Return value
returns true on success, PEAR_Error on failure
Note
This function can not be called statically.
Translation2_Admin::update
Translation2_Admin::update() – Update an existing translation.
Synopsis
require_once 'Admin.php';
mixed Translation2_Admin::update (
string $stringID
, string $pageID
, array $stringArray
)
Description
Update the language details.
Parameter
-
string
$stringID -
ID of the string to translate
-
string
$pageID -
ID of the page (or group) the string to translate belongs to
-
array
$stringArray -
Associative array with string translations:
array(
'en' => 'sample',
'it' => 'esempio',
);
Return value
returns true on success, PEAR_Error on failure
Note
This function can not be called statically.
Translation2_Admin::removePage
Translation2_Admin::removePage() – remove all the translated strings in a page/group
Synopsis
require_once 'Admin.php';
mixed Translation2_Admin::removePage (
string $pageID
= null
)
Description
Remove all the translations for the given pageID.
Parameter
-
string
$pageID -
page/group ID
Return value
returns true on success, PEAR_Error on failure
Note
This function can not be called statically.
Translation2_Admin::cleanCache
Translation2_Admin::cleanCache() – Clear the cache. Use with the CacheLiteFunction decorator only.
Synopsis
require_once 'Admin.php';
void Translation2_Admin::cleanCache (
)
Description
If you use the CacheLiteFunction decorator, you may want to invalidate the cache after a change in the data base.
Note
This function can not be called statically.
Translation2_Admin::getPageNames
Translation2_Admin::getPageNames() – Get a list of all the pageIDs in any table.
Synopsis
require_once 'Admin.php';
array Translation2_Admin::getPageNames (
)
Description
Get a list of all the pageIDs in any table.
Return value
returns array of pageIDs
Note
This function can not be called statically.
Translation2_Admin::getAdminDecorator
Translation2_Admin::getAdminDecorator() – Return an instance of an admin decorator
Synopsis
require_once 'Translation2/Admin.php';
object Decorator& Translation2_Admin::getAdminDecorator (
string $decorator
, object [optional] 1
)
Description
This method is used to get a decorator instance. A decorator can be seen as a filter, i.e. something that can change or handle the values of the objects/vars that pass through.
Parameter
-
string
$decorator -
Name of the decorator
-
object
$obj[optional] -
Object to decorate (the default object being $this)
Return value
returns object Reference of a Translation2_Admin_Decorator subclass
Note
This function can not be called statically.
Class Summary Translation2_Decorator
Class Summary Translation2_Decorator – Decorates a Translation2 class.
Decorates a Translation2 class.
Create a subclass of this class for your own "decoration". The base class acts as a proxy to these methods:
- get()
- getDecorator()
- getLang()
- getLangs()
- getPage()
- getRaw()
- getRawPage()
- getStringID()
- replaceEmptyStringsWithKeys()
- setCharset()
- setContainerOptions() [protected]
- setLang()
- setOption()
- setOptions() [protected]
- setPageID()
- setParams()
- translate()
If you want to "decorate" any of these methods, you have to override them in your custom Decorator.
Class Trees for Translation2_Decorator
- Translation2_Decorator
| Class | Summary |
|---|---|
| Translation2_Decorator_CacheLiteFunction | Decorator to cache fetched data using Cache_Lite_Function class |
| Translation2_Decorator_CacheMemory | Decorator to cache fetched data in memory |
| Translation2_Decorator_DefaultText | Decorator to provide a fallback text for empty strings. |
| Translation2_Decorator_ErrorText | Decorator to provide an error_text message for empty strings. |
| Translation2_Decorator_Iconv | Decorator to switch from/to different encodings. |
| Translation2_Decorator_Lang | Decorator to provide a fallback language for empty strings. |
| Translation2_Decorator_SpecialChars | Decorator to replace special chars with the matching html entities. |
| Translation2_Decorator_UTF8 | Decorator to convert UTF-8 strings to ISO-8859-1 |
Class Summary Translation2_Decorator_CacheLiteFunction
Class Summary Translation2_Decorator_CacheLiteFunction – Decorator to cache fetched data using Cache_Lite_Function class
Cache_Lite_Function Decorator Example
This decorator provides a very efficient cache layer. It requires PEAR::Cache_Lite. It supports all the main options supported by Cache_Lite:
lifeTime[integer]cacheDir[string]fileLocking[boolean]caching[boolean]
If you need to pass an option directly to the Cache_Lite object, you can use setCacheOption().
<?php
$tr = new Translation2($driver, $dbinfo, $params);
$tr =& $tr->getDecorator('CacheLiteFunction');
$tr->setOption('cacheDir', '/var/tmp/');
$tr->setOption('lifeTime', 3600*24*7); //one week
//change a custom Cache_Lite option
$tr->setCacheOption($name, $value);
?>
Class Summary Translation2_Decorator_CacheMemory
Class Summary Translation2_Decorator_CacheMemory – Decorator to cache fetched data in memory
CacheMemory Decorator Example
This decorator provides a memory cache layer. It does NOT persist through requests,
only in the current execution of the script. You can turn off prefetch
if you want small network load (but it will increase the number of queries to the database)
<?php
$tr = new Translation2($driver, $dbinfo, $params);
$tr =& $tr->getDecorator('CacheMemory');
$tr->setOption('prefetch', true); //default value is true
?>
Class Summary Translation2_Decorator_DefaultText
Class Summary Translation2_Decorator_DefaultText – Decorator to provide a fallback text for empty strings.
DefaultText Decorator Example
When the fetched string is empty, it replaces it with the 4th parameter
of the
get()
method, i.e. $defaultText.
If the defaultText parameter is empty too, then return
"$emptyPostfix.$outputString.$emptyPrefix", the three variables
being class properties you can set to a custom string.
When getPage() is called, all the empty strings in the page are replaced by their stringID value.
<?php
$tr = new Translation2($driver, $dbinfo, $params);
$tr =& $tr->getDecorator('DefaultText');
// %stringID% will be replaced with the stringID
// %pageID_url% will be replaced with the pageID
// %stringID_url% will replaced with a urlencoded stringID
// %url% will be replaced with the targeted url
$tr->outputString = '%stringID%<a href="%url%">(T)</a>'; //default: '%stringID%'
$tr->url = '#'; //same as default
$tr->emptyPrefix = '['; //default: empty string
$tr->emptyPostfix = ']'; //default: empty string
?>
Class Summary Translation2_Decorator_ErrorText
Class Summary Translation2_Decorator_ErrorText – Decorator to provide a fallback error_text message for empty strings.
ErrorText Decorator Example
When the fetched string is empty, it replaces it with the contents of the "error_text" column of the langs_avail table
<?php
$tr = new Translation2($driver, $dbinfo, $params);
$tr =& $tr->getDecorator('ErrorText');
?>
Class Summary Translation2_Decorator_Lang
Class Summary Translation2_Decorator_Lang – Decorator to provide a fallback language for empty strings.
Lang Decorator Example
This decorator is very useful when you want to provide a fallback language
for empty strings. It is stackable, so you can have more than one default language.
Use setOption() with the fallbackLang
parameter to specify the fallback language of the current decorator.
<?php
$tr = new Translation2($driver, $dbinfo, $params);
//set English as the main language
$tr->setLang('en');
//set Italian as the first fallback language
$tr =& $tr->getDecorator('Lang');
$tr->setOption('fallbackLang', 'it');
//set Spanish as the second fallback language
$tr =& $tr->getDecorator('Lang');
$tr->setOption('fallbackLang', 'es');
?>
Class Summary Translation2_Decorator_Iconv
Class Summary Translation2_Decorator_Iconv – Decorator to switch from/to different encodings.
Iconv Decorator Example
Use setOption() with the encoding
parameter to specify the target encoding of the current decorator.
<?php
$tr = new Translation2($driver, $dbinfo, $params);
//set Hungarian as the main language
$tr->setLang('hu');
//encode all the strings using the ISO-8859-2 charset
$tr =& $tr->getDecorator('Iconv');
$tr->setOption('encoding', 'ISO-8859-2');
?>
Class Summary Translation2_Decorator_SpecialChars
Class Summary Translation2_Decorator_SpecialChars – Decorator to replace special chars with the matching html entities.
SpecialChars Decorator Example
This decorator replaces special chars with the matching html entities.
Use setOption() with the charset
parameter to specify the target charset of the current decorator (the default
is 'ISO-8859-1'):
<?php
$tr = new Translation2($driver, $dbinfo, $params);
$tr =& $tr->getDecorator('SpecialChars');
$tr->setOption('charset', 'UTF-8');
?>
Class Summary Translation2_Decorator_UTF8
Class Summary Translation2_Decorator_UTF8 – Decorator to convert UTF-8 strings to ISO-8859-1
UTF-8 Decorator Example
This decorator calls utf8_decode() on each string
<?php
$tr = new Translation2($driver, $dbinfo, $params);
$tr =& $tr->getDecorator('UTF8');
?>
Package Translation2 Constants
Package Translation2 Constants – Constants defined in and used by Translation2
All Constants
Constants defined in DecoratorCacheMemory.php
| Name | Value | Line Number |
|---|---|---|
| TRANSLATION2_EMPTY_PAGEID_KEY | 'array_key_4_empty_pageID' | 34 |
| TRANSLATION2_NULL_PAGEID_KEY | 'array_key_4_null_pageID' | 40 |
Constants defined in Translation2.php
| Name | Value | Line Number |
|---|---|---|
| TRANSLATION2_DEFAULT_PAGEID | 'translation2_default_pageID' | 38 |
| TRANSLATION2_ERROR | -1 | 43 |
| TRANSLATION2_ERROR_METHOD_NOT_SUPPORTED | -2 | 44 |
| TRANSLATION2_ERROR_CANNOT_CONNECT | -3 | 45 |
| TRANSLATION2_ERROR_CANNOT_FIND_FILE | -4 | 46 |
| TRANSLATION2_ERROR_DOMAIN_NOT_SET | -5 | 47 |
| TRANSLATION2_ERROR_INVALID_PATH | -6 | 48 |
| TRANSLATION2_ERROR_CANNOT_CREATE_DIR | -7 | 49 |
| TRANSLATION2_ERROR_CANNOT_WRITE_FILE | -8 | 50 |
| TRANSLATION2_ERROR_UNKNOWN_LANG | -9 | 51 |