45 lines
1.5 KiB
PHP
45 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Service;
|
|
|
|
use Hyperf\Cache\Cache;
|
|
use Hyperf\Contract\TranslatorInterface;
|
|
use Hyperf\Contract\TranslatorLoaderInterface;
|
|
use Hyperf\Translation\Translator;
|
|
use App\Model\Translation as tModel;
|
|
use Psr\Container\ContainerInterface;
|
|
use function Hyperf\Config\config;
|
|
|
|
class TranslationService extends Translator implements TranslatorInterface
|
|
{
|
|
protected Cache $cache;
|
|
|
|
public function __construct(TranslatorLoaderInterface $loader, ContainerInterface $container)
|
|
{
|
|
parent::__construct($loader, 'zh_CN');
|
|
$this->cache = $container->get(Cache::class);
|
|
}
|
|
|
|
public function get($key, array $replace = [], $locale = null, $fallback = true): array|string
|
|
{
|
|
$locale = $locale ?: $this->getLocale();
|
|
|
|
$cacheKey = "lang:{$locale}:{$key}";
|
|
// 先查缓存
|
|
$cached = $this->cache->get($cacheKey);
|
|
if ($cached !== null) {
|
|
return $this->makeReplacements($cached, $replace);
|
|
}
|
|
// 查数据库
|
|
$value = tModel::getLangValue($locale, $key);
|
|
if ($value) {
|
|
$this->cache->set($cacheKey, $value, (int)config("translation.ttl"));
|
|
return $this->makeReplacements($value, $replace);
|
|
}
|
|
// 文件翻译
|
|
$fallbackValue = parent::get($key, $replace, $locale, $fallback);
|
|
// fallback 结果也缓存
|
|
$this->cache->set($cacheKey, $fallbackValue, (int)config("translation.ttl"));
|
|
return $fallbackValue;
|
|
}
|
|
} |