gpt4 book ai didi

php - Laravel 扩展供应商类

转载 作者:可可西里 更新时间:2023-11-01 00:54:28 26 4
gpt4 key购买 nike

我尝试扩展一个 Illuminate 类翻译器

我创建了一个类并扩展到翻译器然后我将这一行添加到我的 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;
}

所以我的绑定(bind)必须通过接口(interface)..无法实例化

 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绑定(bind)。

您也可以覆盖它。

$this->app->bind('translator', function(){
return new \App\Repositories\Translation\TranslationTranslator;
})

关于php - Laravel 扩展供应商类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52312759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com