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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度