1

I'm trying to make proper use of Laravel's Service Container to instantiate a connection to a third-party API and use it across my Controllers. Below I added my API connection into the register method of Laravel's AppServiceProvider. In my Controller constructor, I provide a handle to that connection that can be used freely inside the Controller wherever a connection is needed. Does this example demonstrate the best use of a Service Container? Should I replace my reference to 'bind' with 'singleton' instead?

use App\Http\Clients\RestClient;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(RestClient::class, function($app)
        {
            $this->api = new RestClient();
            $this->api->setUrl(getenv('API_REST_URL'))
                    ->setUsername(getenv('API_USERNAME'))
                    ->setPassword(getenv('API_PASSWORD'))
                    ->connect();

            return $this->api;
        });
    }
} 

class LoginController extends Controller 
{
    public function __construct(RestClient $api) 
    {
        $this->api = $api;
    }

    public function postLogin() 
    {
        $results = $this->api->search('Users');
    }
}
0

1 Answer 1

1

Your usage is not wrong. But, this usage stands against Dependency Injection. You don't need to use custom service provider. But you can inject RestClient by using Laravel's class registration.

Here is an example from Laravel's documentation. You can setup RestClient here and you can inject it to RestApiService as well.

$this->app->singleton(Connection::class, function ($app) {
    return new Connection(config('riak'));
});
Sign up to request clarification or add additional context in comments.

5 Comments

I have something like the above in my ServiceProvider using the RestAPIService but it makes no difference. $this->app->bind('App\Services\RestApiService', function ($app) { return new RestApiService(); }); If I don't use the ServiceProvider and setup the RestClient in the singleton, where does the singleton live?
Why don't you inject RestClient to RestApiService when you are registering/binding class? Your example of course won't any difference. So RestApiService will get RestClient $restClient parameter, which already initialized. You won't need to create a new class for it.
@KarlHill this is what i want to say. You can also use your legacy RestApiService. And you can inject this service to your controller, instead of injecting 3rd party client. Your current usage is much better than previous. I would like to learn if there is any other way to inject.
@terasakyan Thank you. Have you tried Laravel Passport?
@KarlHill yes :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.