如何在CakePHP中使用TranslateBehavior? [英] How do I use the TranslateBehavior in CakePHP?

查看:171
本文介绍了如何在CakePHP中使用TranslateBehavior?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有关于cakephp.org的文档,我在google上找不到一个。请链接我一些文档或提供一个!

There is no documentation on cakephp.org and I am unable to find one on google. Please link me some documentation or supply one!

推荐答案

翻译行为是另一个CakePHP的非常有用但记录不多的功能。

The translate behavior is another of CakePHP's very useful but poorly documented features. I've implemented it a couple of times with reasonable success in multi-lingual websites along the following lines.

首先,翻译行为只会将您的数据库内容进行国际化现场。如果你有更多的静态内容,你可以看看Cake的 __('string')包装函数和 gettext (有关此此处的一些实用信息

Firstly, the translate behavior will only internationalize the database content of your site. If you've any more static content, you'll want to look at Cake's __('string') wrapper function and gettext (there's some useful information about this here)

假设我们要用以下db表翻译内容:

Assuming there's Contents that we want to translate with the following db table:

CREATE TABLE `contents` (
    `id` int(11) unsigned NOT NULL auto_increment,
    `title` varchar(255) default NULL,
    `body` text,
  PRIMARY KEY  (`id`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

content.php模型具有:

The content.php model then has:

var $actsAs = array('Translate' => array('title'   => 'titleTranslation',
                     'body'    => 'bodyTranslation'
                     ));

然后需要将i18n表添加到数据库中:

in its definition. You then need to add the i18n table to the database thusly:

CREATE TABLE `i18n` (
  `id` int(10) NOT NULL auto_increment,
  `locale` varchar(6) NOT NULL,
  `model` varchar(255) NOT NULL,
  `foreign_key` int(10) NOT NULL,
  `field` varchar(255) NOT NULL,
  `content` mediumtext,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

然后当您将数据保存到控制器中的数据库时,将语言环境设置为语言你想要(这个例子是波兰语):

Then when you're saving the data to the database in your controller, set the locale to the language you want (this example would be for Polish):

$this->Content->locale = 'pol';
$result = $this->Content->save($this->data);

这将在i18n表中为pol区域设置的标题和正文字段创建条目。查找将根据用户浏览器中设置的当前语言环境查找,返回如下数组:

This will create entries in the i18n table for the title and body fields for the pol locale. Finds will find based on the current locale set in the user's browser, returning an array like:

[Content]
  [id]
  [titleTranslation]
  [bodyTranslation]

p28n组件实施语言切换解决方案与gettext和翻译行为非常相似。

We use the excellent p28n component to implement a language switching solution that works pretty well with the gettext and translate behaviours.

这不是一个完美的系统 - 因为它在运行时创建HABTM关系,您可能已手动创建的其他关系,但如果您小心,它可以很好地工作。

It's not a perfect system - as it creates HABTM relationships on the fly, it can cause some issues with other relationships you may have created manually, but if you're careful, it can work well.

这篇关于如何在CakePHP中使用TranslateBehavior?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆