zaszczyk/translatable

该包最新版本(1.0.1)没有提供许可证信息。

使用Phalcon模型管理可翻译字段。从https://github.com/ovide/translatable分叉而来

1.0.1 2018-04-23 21:10 UTC

This package is auto-updated.

Last update: 2024-08-29 01:01:05 UTC


README

使用Phalcon模型管理可翻译字段

示例

您有一个数据库表 MyModel,包含列 idvaluetimestampdescription;但 description 必须是一个可翻译字段。

您可以添加一个Translation表,如下所示

CREATE TABLE `translation` (
  `table` varchar(255) NOT NULL,
  `field` varchar(255) NOT NULL,
  `row` varchar(255) NOT NULL,
  `lang` char(2) NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY (`table`,`field`,`row`,`lang`)
)
use \Ovide\Lib\Translate as Translate;

/**
 * Your translatable model
 * @property string $description
 */
class MyModel extends Translate\Model
{
    public $id;
    public $value;
    public $timestamp;
    protected $_translatable = ['description'];
}

/**
 * This is a default basic abstract model, but you can add yours
 */
class Translation extends Translate\Adapter\Model\AbstractModel{}


$di = new \Phalcon\DI\FactoryDefault();
$di->setShared('db', function () {
    return new \Phalcon\Db\Adapter\Pdo\Mysql([/* my config */]);
});

/**
 *             HERE WE SET THE TRANSLATOR
 */
$di->setShared('translator', function() {
    $service = new Translate\Service();
    //All translatable models from 'db'
    //will use 'Translation' to manage the translations
    $service->attachAdapter(
        'db',
        Translate\Adapter\Model\Manager::class,
        ['backendModel' => 'Translation']
    );
    //You can use a default language resolver
    Translate\Model::setLanguageResolver(function() use($di){
        //You can put anything here
        if (isset($_COOKIE['lang'])) return $_COOKIE['lang'];
        return 'en';
    });
});

现在您可以使用可翻译字段作为普通属性

$model = new MyModel();
$model->value = 'foo';
//Will set the text using the default language
$model->description = 'my description';
//You can change the current language
$model->setCurrentLang('es');
$model->description = 'mi descripción';
//Or use setter/getter
$model->setTranslation('description', 'la meva descipció', 'ca');
$model->save();

适配器

您可以使用任何适配器来存储翻译。目前有一个模型(SQL)和集合(Mongo)适配器。只需实现TranslationInterface即可创建自己的适配器。

interface TranslationInterface
{
    public static function retrieve(Model $model, $pk, array $options = null);
    public function get($field, $language);
    public function set($field, $language, $value);
    public function persist(array $records = null);
    public function remove();
}