skip to Main Content

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


  1. Since the __construct() method in your Party class has a parameter PartyRingService $partyRingService you would need to pass that in when you create a new instance of your Party class.

    So something like

    $partyRingService = ... // get/create the party ring service instance
    $party = new Party($partyRingService);
    
    Login or Signup to reply.
  2. You have to use this in your controller:

    $party = resolve(Party::class);
    

    And that will work for you

    Login or Signup to reply.
  3. I am not totally sure, but shouldn’t you add PartyRingService when resolving Party class

        {
            $this->app->singleton('AppParty', function ($app) {
                return Party($app->make(PartyRingService::class));
            });
        }
    
    Login or Signup to reply.
  4. Make sure that you have imported the Party class and the PartyRingService class at the top of your controller file:

    use AppParty;
    use AppServicesPartyRingService;
    

    This assumes that the Party class and the PartyRingService class are present in the correct namespace.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search