我尝试扩展Illuminate Class Translator
我创建了一个类并扩展到翻译器
然后我将此行添加到我的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 with message
‘Target [Illuminate\Translation\LoaderInterface] is not instantiable
while building [App\Repositories\Translation\TranslationTranslator].’
解决方法:
您可以使用闭包来解析类
$this->app->bind(\Illuminate\Translation\Translator::class, function(){
return new \App\Repositories\Translation\TranslationTranslator;
});
其次,使用翻译器别名将翻译器与laravel绑定.
您也可以覆盖它.
$this->app->bind('translator', function(){
return new \App\Repositories\Translation\TranslationTranslator;
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。