Gar*_*ian 6 php translation laravel
我尝试扩展 Illuminate Class Translator
我创建了一个类并扩展到翻译器,然后将此行添加到我的 RepositoryServiceProvider
$this->app->bind(\Illuminate\Translation\Translator::class, \App\Repositories\Translation\TranslationTranslator::class);
Run Code Online (Sandbox Code Playgroud)
但它不起作用
我究竟做错了什么?
类如下
<?php
namespace App\Repositories\Translation;
use Countable;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Collection;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Support\NamespacedItemResolver;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\TranslatorInterface;
class TranslationTranslator extends \Illuminate\Translation\Translator
{
/**
* Parse a key into namespace, group, and item.
*
* @param string $key
* @return array
*/
public function parseKey($key)
{
\Log::info('got in');
die;
$segments = parent::parseKey($key);
if (is_null($segments[0])) {
$segments[0] = @explode('.', $segments[2])[0];
}
if ($segments[1] == 'translatable') {
$segments[1] = @explode('.', $segments[2])[0] . '_' . @explode('.', $segments[2])[1];
}
return $segments;
}
}
Run Code Online (Sandbox Code Playgroud)
更新
显然 Translator 类有一个构造函数
public function __construct(LoaderInterface $loader, $locale)
{
$this->loader = $loader;
$this->locale = $locale;
}
Run Code Online (Sandbox Code Playgroud)
所以我的绑定必须通过接口..无法实例化
public function boot()
{
$app = $this->app;
$this->app->bind(\Illuminate\Translation\Translator::class, function() use ($app){
return $app->make(\App\Repositories\Translation\TranslationTranslator::class);
});
}
Run Code Online (Sandbox Code Playgroud)
并收到此错误
Illuminate\Contracts\Container\BindingResolutionException 消息“Target [Illuminate\Translation\LoaderInterface] 在构建 [App\Repositories\Translation\TranslationTranslator] 时不可实例化。”
尝试将其更改为这样:
$this->app->instance(\Illuminate\Translation\Translator::class, \App\Repositories\Translation\TranslationTranslator::class);
Run Code Online (Sandbox Code Playgroud)
然后应该更改接口的实例。
更新
如果您只是想添加一个新方法,则 Translator 类是 Macroable。所以你可以执行以下操作
Translator::macro('parseKey', function ($key) {
\Log::info('got in');
die;
$segments = parent::parseKey($key);
if (is_null($segments[0])) {
$segments[0] = @explode('.', $segments[2])[0];
}
if ($segments[1] == 'translatable') {
$segments[1] = @explode('.', $segments[2])[0] . '_' . @explode('.', $segments[2])[1];
}
return $segments;
});
Run Code Online (Sandbox Code Playgroud)
然后您就可以像平常一样调用您的方法。例如:
app(Translator::class)->parseKey($key);
Run Code Online (Sandbox Code Playgroud)