avasin
avasin

Reputation: 9726

Laravel: how to fix interface is not instatiable error?

I have extended standard laravel Translator class and i need to create it with dependencies. When i make standard Translator class, it works like a charm:

app()->make('Illuminate\Translation\Translator')

But when i try to make my custom class, i get Illuminate\Translation\LoaderInterface is not instantiable error:

app()->make('App\Services\MyTranslator')

Why do i get such error, while LoaderInterface works for standard Translator class?

Upvotes: 0

Views: 430

Answers (1)

patricus
patricus

Reputation: 62238

You're getting that error because the constructor has type hinted an interface, but you have not told Laravel how to resolve that interface. Since you haven't told it how to resolve the interface, Laravel tries to instantiate it directly, which gives the error.

The built in translator has a service provider which tells Laravel how to create the Translator object. You can take a look at it at Illuminate/Translation/TranslationServiceProvider.php.

So, you need to create a service provider for your translator.

Create a new file app/Providers/MyTranslationServiceProvider.php. The file should look something like this:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class MyTranslationServiceProvider extends ServiceProvider {

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('App\Services\MyTranslator', function($app)
        {
            $loader = $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 = $app['config']['app.locale'];

            $trans = new \App\Services\MyTranslator($loader, $locale);

            $trans->setFallback($app['config']['app.fallback_locale']);

            return $trans;
        });
    }
}

The code is pretty much copied from Laravel translation service provider. You can change whatever you need to to setup your object correctly.

Now, edit your config/app.php file to add your new service provider to the providers array.

Now you should be good to go. You can read more about service providers here.

Upvotes: 1

Related Questions