我在laravel
中有一个服务提供商,该服务提供商从locale
读取所有可用的语言,并将它们保存在缓存文件中。一切正常,但所有翻译均为德语。我希望以de
和en
语言获得它们。
这是ServiceProvider
中的代码:
$minutes = 24 * 60;
Cache::remember('translations', $minutes, function () {
$directories = array('de', 'en');
$collection = new \stdClass;
foreach ($directories as $directory) {
$path = resource_path('lang/' . $directory);
$allTranslations = collect(File::allFiles($path))->flatMap(function ($file, $directory) {
return [
($translation = $file->getBasename('.php')) => trans($translation, array(), null, $directory),
];
});
$allModuleTranslations = collect(File::allFiles($path . '/modul'))->flatMap(function ($file, $directory) {
return [
($translation = $file->getBasename('.php')) => trans('modul/' . $translation, array(), null, $directory),
];
});
$collection->$directory = $allTranslations->merge($allModuleTranslations);
}
return json_encode($collection);
});
有人可以看到为什么它返回所有德语单词吗?
结果如下:
{
de:
auth:
failed: "Diese Zugangsdaten wurden nicht in unserer Datenbank gefunden."
throttle: "Zu viele Login Versuche. Versuchen Sie es bitte in :seconds Sekunden."
en:
auth:
failed: "Diese Zugangsdaten wurden nicht in unserer Datenbank gefunden."
throttle: "Zu viele Login Versuche. Versuchen Sie es bitte in :seconds Sekunden."
}
答案 0 :(得分:1)
您必须使用$directory
从父范围导入use
变量,它不会与flatMap()
回调一起传递
trans仅具有3个参数,但您要传递4个参数
mixed trans(string $key, array $replace = [], string|null $locale = null)
这应该有效:
$minutes = 24 * 60;
Cache::remember('translations', $minutes, function () {
$directories = array('de', 'en');
$collection = new \stdClass;
foreach ($directories as $directory) {
$path = resource_path('lang/' . $directory);
$allTranslations = collect(File::allFiles($path))
->flatMap(function ($file) use ($directory) {
return [
($translation = $file->getBasename('.php')) => trans($translation, array(), $directory),
];
});
$allModuleTranslations = collect(File::allFiles($path . '/modul'))
->flatMap(function ($file) use ($directory) {
return [
($translation = $file->getBasename('.php')) => trans('modul/' . $translation, array(), $directory),
];
});
$collection->$directory = $allTranslations->merge($allModuleTranslations);
}
return json_encode($collection);
});