Dependency injecting a service within another service in laravel

Viewed 31

#Background

Hi,

I've got a laravel codebase I've inherited. There are some third party APIs being used for assorted data services and I am attempting to make the software more testable. Some of these API calls are handled via clients and are shared using services.

In order to continue the testing, some services will need to call other services. With this I also am attempting to dependency inject them. I am having issues doing this.

Setup

  • laravel/framework: "^8.0.0

Question

The following Service needs to be able to dependency inject another service in functions.


namespace App\Services\ExampleService;

use App\Services\ExampleDependantService;

class SyncProfile
{
    // ...
}

I have attempted to inject at a function level (this is preferred):

    public function sync(ExampleDependantService $exampleDependantService, /*...*/)
    {
        // ...
    }

I've also attempted to set this up at a class/constructor level:


    protected ExampleDependantService $exampleDependantService;

    public function __construct(ExampleDependantService $exampleDependantService)
    {
        $this->exampleDependantService = $exampleDependantService;
    }

Both of these are unable to resolve the ExampleDependantService when tested, giving errors such as:

  • ArgumentCountError : Too few arguments to function App\Services\ExampleService\SyncProfile::__construct(), 0 passed in [..]/SyncProfileTest.php on line 96 and exactly 1 expected ..

To be clear, the ExampleDependantService is registered in config/app.php


'providers' => [
    // ...
    App\Services\ExampleDependantService::class
    // ...

Desired situation

  • I should be able to call $exampleService->sync() in normal usage
  • I should be able to call $exampleService->sync($mockedExampleDependantService) in test usage

Can anyone help with this?

Thanks in advance

0 Answers
Related