我想出了一个解决方案,创建一个自定义插件来扩展十月 CMS 后端翻译服务。我在插件的 boot() 方法中添加了以下代码:
// Custom Backend Translator that handles the Backend localisation with the Rainlab Translator plugin
$this->app->singleton('translator', function ($app) {
$loader = $app['translation.loader'];
// When registering the translator component, we'll need to set the default
// locale as well as the fallback locale. So, we'll grab the application
// configuration so we can easily get both of these values from there.
$locale = $app['config']['app.locale'];
// extending October CMS Translator class
$trans = new Translator($loader, $locale);
// setting locale to message
Message::$locale = $locale;
$trans->setFallback($app['config']['app.fallback_locale']);
return $trans;
});
我创建了一个 Translator 类,它扩展了默认类并实现了数据库查找翻译。如果没有找到翻译,它还会回退到基于默认数组文件的翻译。
<?php namespace Author\MyPlugin\Classes\Translation;
use Author\MyPlugin\Classes\Translation\Message as Message;
class Translator extends \October\Rain\Translation\Translator
{
/**
* Get the translation for the given key.
*
* @param string $key
* @param array $replace
* @param string $locale
* @return string
*/
public function get($key, array $replace = [], $locale = null)
{
// getting translation from database
$message = Message::trans($key);
// if there's a translation we return it
if ($message != null && $message !== $key) {
return $message;
}
// otherwise fallback to file array translations
return parent::get($key, $replace, $locale);
}
}
以及Message类的代码如下:
<?php namespace Author\MyPlugin\Classes\Translation;
class Message extends \RainLab\Translate\Models\Message
{
/**
* Creates or finds an untranslated message string.
* @param string $messageId
* @return string
*/
public static function get($messageId)
{
if (!self::$locale) {
return $messageId;
}
if (!is_string($messageId)) {
return null;
}
// we let full translation key for the backend
if (!\App::runningInBackend()) {
$messageCode = self::makeMessageCode($messageId);
} else {
$messageCode = $messageId;
}
/*
* Found in cache
*/
if (array_key_exists($messageCode, self::$cache)) {
return self::$cache[$messageCode];
}
/*
* Uncached item
*/
$item = static::firstOrNew([
'code' => $messageCode
]);
/*
* Create a default entry
*/
if (!$item->exists) {
$data = [static::DEFAULT_LOCALE => $messageId];
$item->message_data = $item->message_data ?: $data;
}
/*
* Schedule new cache and go
*/
$msg = $item->forLocale(self::$locale, $messageId);
self::$cache[$messageCode] = $msg;
self::$hasNew = true;
return $msg;
}
}
欢迎对此解决方案的任何反馈。