我尝试扩展照明类翻译器
我创建了一个类并扩展到翻译器 然后将这行添加到我的RepositoryServiceProvider
$this->app->bind(\Illuminate\Translation\Translator::class, \App\Repositories\Translation\TranslationTranslator::class);
但是它不起作用
我在做什么错了?
该类如下
<?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;
}
}
更新
显然Translator类具有构造函数
public function __construct(LoaderInterface $loader, $locale)
{
$this->loader = $loader;
$this->locale = $locale;
}
所以我的绑定必须通过该接口..无法实例化
public function boot()
{
$app = $this->app;
$this->app->bind(\Illuminate\Translation\Translator::class, function() use ($app){
return $app->make(\App\Repositories\Translation\TranslationTranslator::class);
});
}
并收到此错误
带有消息的Illuminate \ Contracts \ Container \ BindingResolutionException '目标[Illuminate \ Translation \ LoaderInterface]无法实例化 在构建[App \ Repositories \ Translation \ TranslationTranslator]时。”
答案 0 :(得分:2)
您可以使用闭包来解析类
$this->app->bind(\Illuminate\Translation\Translator::class, function(){
return new \App\Repositories\Translation\TranslationTranslator;
});
第二个翻译器使用translator
别名与laravel绑定。
您也可以覆盖它。
$this->app->bind('translator', function(){
return new \App\Repositories\Translation\TranslationTranslator;
})
答案 1 :(得分:2)
这对我有用
$app = $this->app;
$loader = $app['translation.loader'];
$locale = $app['config']['app.locale'];
$this->app->bind('translator', function() use ($loader, $locale){
return new \App\Repositories\Translation\TranslationTranslator($loader, $locale);
});
希望对您有帮助
答案 2 :(得分:0)
检查以下示例
namespace App\Repositories\Translation;
use Illuminate\Translation\Translator;
class TranslationTranslator extends Translator
{
public function get()
{
....
}
}
不需要任何东西。您只需要添加新功能或覆盖基类功能。然后,您可以将该类用作简单的其他类。