I am currently having some issues setting up some dependency injection for a new service I have made.
I am trying to get PartyRingService
to inject into a constructor without me passing it in.
I have tried the following in my PartyRingServiceProvider
:
class PartyRingServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
$this->app->singleton('AppServicesPartyRingService', function ($app) {
return new PartyRingService();
});
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}
I have added to config/app.php
my new service provider to the providers array:
/*
* Application Service Providers...
*/
......
AppProvidersPartyRingServiceProvider::class,
And this is the constructor where I am trying to inject my service:
This is the class where I am trying to use my new service in the constructor:
class Party
{
private PartyRingService $partyRingService;
public function __construct(PartyRingService $partyRingService)
{
$this->partyRingService = $partyRingService;
}
...
}
However, I am getting the following error when I am trying to use PartyService
:
ArgumentCountError PHP 8.2.7
10.13.5 Too few arguments to function AppParty::__construct(), 0 passed in
/var/www/html/app/Http/Controllers/PartyController.php on line 28
and exactly 1 expected
This is what line 28 of PartyController
looks like:
$party = new Party();
I feel like I am just missing a step here, so if someone could help me identify it, that would be great, thank you.
4
Answers
Since the
__construct()
method in yourParty
class has a parameterPartyRingService $partyRingService
you would need to pass that in when you create a new instance of your Party class.So something like
You have to use this in your controller:
And that will work for you
I am not totally sure, but shouldn’t you add PartyRingService when resolving Party class
Make sure that you have imported the Party class and the PartyRingService class at the top of your controller file:
This assumes that the Party class and the PartyRingService class are present in the correct namespace.