我要扩展Illuminate\Translation\Translator
的此类\Illuminate\Support\NamespacedItemResolver
<?php
namespace Illuminate\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 Illuminate\Contracts\Translation\Translator as TranslatorContract;
class Translator extends NamespacedItemResolver implements TranslatorContract
{
use Macroable;
}
我将\Illuminate\Support\NamespacedItemResolver
扩展到了自己的课程
但是当我调用Translator
时,它仍然具有基类的功能。
就是\Illuminate\Support\NamespacedItemResolver
。
<?php
namespace App\Repositories;
class NamespaceParser extends \Illuminate\Support\NamespacedItemResolver
{
}
更新
创建了一个新的Translator类,并尝试在AppServiceProvider
中对其进行扩展
以及以下 WORKED
public function register()
{
$loader = $this->app['translation.loader'];
// When registering the translator component, we'll need to set the default
// locale as well as the fallback locale. So, we'll grab the application
// configuration so we can easily get both of these values from there.
$locale = $this->app['config']['app.locale'];
$this->app->extend('translator', function () {
new \App\Repositories\Translator($loader, $locale);
});
}
答案 0 :(得分:1)
您尝试实现的是高级功能,并在此处进行了描述:
https://laravel.com/docs/5.7/container#extending-bindings
可以在此处找到执行此操作的程序包示例:
https://github.com/onlinepets/laravel-conditional-migrations/blob/master/src/ServiceProvider.php
您必须告诉Laravel从现在开始使用您的自定义类,而不是默认类。
摘要
您必须告诉Laravel服务容器使用不同于正常的其他类。您可以通过在服务提供商的注册功能中调用$this->app->extend
来完成此操作。
答案 1 :(得分:0)
此代码在Laravel 6中对我有用:
public function register()
{
$this->app->extend(\Illuminate\Translation\Translator::class, function ($translator) {
return new \App\Translation\Translator($translator->getLoader(), $translator->getLocale());
});
}
应添加到app/Providers/AppServiceProvider.php