I'm trying to create ServiceProvider for duplicated code in my Laravel application. My solution throws an exception:
Illuminate \ Contracts \ Container \ BindingResolutionException:
Unresolvable dependency resolving [Parameter #0 [ <required> string $shortName ]] in class App\Domain\Translation\GetTranslation
I have a custom abstract controller where I have a simple singleton function:
namespace App\Http\Controllers\WWW;
class CustomController {
(...)
app()->singleton(
GetTranslation::class, function() {
return new GetTranslation(
TrimSuffixFromUrl::getShortName(),
LanguageMap::getLanguageIdByCode(\LaravelLocalization::getCurrentLocale()),
app()->make(CurrentLanguage::class)
);
});
(...)
}
This singleton is used in a concrete controller named CreateAccount:
class CreateAccount extends ControllerWWW
{
public function index(Request $request, DbInstanceFactory $dbInstance, GetTranslation $translation)
{
$getTranslation = $translation; // For simplify this example I remove logic
// (...)
}
I want to create ServiceProvider
:
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Domain\Domains\Prefix\TrimSuffixFromUrl;
use App\Domain\Language\CurrentLanguage;
use App\Domain\Translation\GetTranslation;
use App\Repository\LanguageMap;
use Illuminate\Support\ServiceProvider;
/**
* Class TranslatioServiceProvider
* @package App\Providers
*/
class TranslationServiceProvider extends ServiceProvider
{
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register(): void
{
app()->singleton(
GetTranslation::class, function() {
return new GetTranslation(
TrimSuffixFromUrl::getShortName(),
LanguageMap::getLanguageIdByCode(\LaravelLocalization::getCurrentLocale()),
app()->make(CurrentLanguage::class)
);
}
);
}
/**
* @return array
*/
public function provides(): array
{
parent::provides();
return [GetTranslation::class];
}
}
And I add this service to app.php
:
'providers' => [
App\Providers\TranslationServiceProvider::class,
]
I know the Laravel tries to resolve dependencies for this service but I don't know how to write this code to resolve primitives in a controller.
In other hand, this class - GetTranslation
- is connected with my views, for example:
<?php
// resources/lang/br/validation.php
declare(strict_types=1);
$translation = app()->make(\App\Domain\Translation\GetTranslation::class);
return [
'required' => $translation->getTranslationsByKey('tranlation_my_key')
];
How to run this service provider in controller and in views - but i don't need run ->singleton()
method in abstract controller. I think the place for this method is in Provider folder, not in controllers.