0

I am using Laravel Lumen (v8.2.4) with PHP (v7.4) I have the following controller class:

<?php

namespace App\Http\Controllers;

use App\Services\MyService;

class MyController extends Controller
{
    protected $myService;

    public function __construct(MyService $myService)
    {
        $this->myService = $myService;
    }

}

And the following service class:

<?php

namespace App\Services;

class MyService
{
    private $credentials;

    function __construct($credentials)
    {
        $this->credentials = $credentials;
    }
}

The myService class requires the credentials property to be set in order to function correctly. When myService is being injected into my controller class, I don't have the credentials at that time so therefore cannot initialise the service class to inject it.

How can I handle this? Should I remove the service class constructor and set the credentials property in a public setter method and invoke this when I need to? I am not sure if this is a good approach.

Appreciate any advice.

Mr B
  • 3,980
  • 9
  • 48
  • 74

1 Answers1

1

You need to register your service in service provider. You can do it in AppServiceProvider or in custom provider.

//retrieve credentials from wherever you need to get them, ex: config file
$credentials = config('app.credentialts');

$this->app->bind(MyService::class, function ($app) use ($credentials) {
    return new MyService($credentials);
});

Check out Laravel Service Providers and Laravel Service Containers for more detailed information.

  • Thanks for the info. In my case, I will be retrieving the credentials based on a URL parameter. This parameter will then be used to retrieve the credentials from the database. Do you know how can I do this from within the AppServiceProvider? – Mr B Feb 24 '22 at 14:32
  • 1
    Lets say if you have url like this **https://example.com/some-path?username=test** then you can get it via **request()** helper like this **request()->username** .Then you can perform your query to DB. – Sona Khachatryan Feb 24 '22 at 14:50