douzhang1299 2018-11-30 10:27
浏览 453
已采纳

如何扩展laravel Illuminate \ Translation \ Translator类

I want to extend this class Illuminate\Translation\Translator which extends \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;
}

I extended \Illuminate\Support\NamespacedItemResolver into my own class

but when I call Translator its still taking the base class's functions. which is \Illuminate\Support\NamespacedItemResolver.

<?php

namespace App\Repositories;

class NamespaceParser extends \Illuminate\Support\NamespacedItemResolver
{
}

UPDATE

created a new Translator class and tried to extend it in the AppServiceProvider and the below 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);
       });
   }
  • 写回答

1条回答 默认 最新

  • doutanghuan9595 2018-11-30 10:41
    关注

    What you try to achieve is kind of advanced and is described here:

    https://laravel.com/docs/5.7/container#extending-bindings

    An example of a package that does this very thing can be found here:

    https://github.com/onlinepets/laravel-conditional-migrations/blob/master/src/ServiceProvider.php

    You have to tell Laravel to use your custom class from now on, instead of the default one.

    Summary

    You have to tell the Laravel Service Container to use another class than normal. You do this by calling $this->app->extend in the register function of a Service Provider.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘