Laravel class 配置文件中不存在转换器

Laravel class translator does not exist in a configuration file

是否有任何方法允许在 应用程序的 配置文件 中插入可翻译的值?

我在 config/fox-reports.php 有一个 custom 配置文件,我正在尝试设置一个可翻译的配置值,如下所示:

return [
    'attrs' => [
       'Product' => __('Product Title')
    ]
] 

当我运行php artisan config:cache时产生如下错误:

In Container.php line 729:

  Class translator does not exist

您不能在配置文件中使用 __() 助手,因为它使用 Translator class。 Laravel 在大多数服务尚未初始化时,在循环的最开始加载配置。

为了完整起见,为了补充 Alexey 的回答,像这样的翻译应该在以后处理。使用默认值设置配置文件,如果不存在翻译,将使用该默认值。

config/fox-reports.php

return [
    'attrs' => [
       'Product' => 'Product Title'
    ]
];

然后在您的localization JSON files中设置翻译键,例如

resources/lang/fr/fr.json

{
    "Product Title": "Titre de produit"
}

并且在您的控制器或任何地方,您将对 config() 的调用包装在翻译函数中:

// not like this:
// $title = config('foxreports.attrs.Product');
// but like this:
$title = __(config('foxreports.attrs.Product'));

如果您需要让自动本地化工具检测到默认值,只需将其添加到存根 class 某处,例如

<?php

namespace App\Stubs;

class Localization
{
    public method __construct()
    {
        __('Product Title');
    }
}