SPQRInc
SPQRInc

Reputation: 198

Provide API-Client to Controller

I am using Laravel to call an external API.

This is my Client:

<?php

use GuzzleHttp\Client;

$client = new Client();

$response = $client->request('POST',
    'https://example.org/oauth/token', [
        'headers'     => [
            'cache-control' => 'no-cache',
            'Content-Type'  => 'application/x-www-form-urlencoded',
        ],
        'form_params' => [
            'client_id'     => '2',
            'client_secret' => 'client-secret',
            'grant_type'    => 'password',
            'username'      => 'username',
            'password'      => 'password',
        ],
    ]);

$accessToken = json_decode((string)$response->getBody(),
    true)['access_token'];

Now I can use this to fetch something:

<?php
$response = $client->request('GET',
    'https://example.org/api/items/index', [
        'headers' => [
            'Accept'        => 'application/json',
            'Authorization' => 'Bearer '.$accessToken,
        ],
    ]);

So now I don't want to initiate the client on every method again. So maybe there's a cool/Laravel-like way to provide the $client to the controller on specific routes?

I thought about an app service provider or an middleware, but I'd love to see an example :-)

Upvotes: 2

Views: 146

Answers (1)

ajthinking
ajthinking

Reputation: 4648

Perhaps you can use singleton? Wrap your implementation in a class lets say YourHttpClient then in your AppServiceProviders register method add:

$this->app->singleton('YourHttpClient', function ($app) {
    return new YourHttpClient();
});

Then you should be able to typehint it in your controller constructors like this

class SomeController {
    private $client;

    public function __construct(YourHttpClient $client) {
       $this->client = $client;
    }
}

Upvotes: 1

Related Questions