I have a service provider that creates an instance of a class with a Guzzle Client injected into it but the bind method is never called and I am not sure why or how to debug it.
BaseServiceProvider.php
<?php
namespace App\Providers;
use GuzzleHttp\Client;
use Illuminate\Support\ServiceProvider;
use App\Services\BaseService;
use Illuminate\Support\Facades\Log;
class BaseServiceProvider extends ServiceProvider
{
public function register()
{
Log::info('In register 1');
$this->app->bind(BaseService::class, function ($app) {
Log::info('In binding');
return new BaseService(
new Client(
[
'base_uri' => config('api.url')
]
)
);
});
}
}
<?php
namespace App\Services;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
class UserService extends BaseService
{
public function show(string $id) : JsonResponse
{
try {
return $this->request('GET', "users/{$id}");
} catch (\Exception $error) {
return response()->json([
'error' => true,
'msg' => 'There was an error.',
], 500);
}
}
}
<?php
namespace App\Services;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
class BaseService
{
/**
* @var Client
*/
protected $client;
/**
* The baseService constructor.
*
* @param Client $client The guzzleHTTP client.
* @return void
*/
public function __construct(Client $client)
{
$this->client = $client;
}
/**
* Sends a request.
* @param string $method The method.
* @param string $url The url, not including the base uri.
* @param array $payload Optional array of params to send.
* @param boolean $decodePayload Optional array of params to send.
* @return \Illuminate\Http\JsonResponse
* @throws \GuzzleHttp\Exception\GuzzleException Throws a guzzle error.
*/
public function request(
string $method,
string $url,
array $payload = []
) {
try {
$response = $this->client->request(
strtoupper($method),
$url,
[
'json' => $payload,
'headers' => [
'Authorization' => 'Bearer 123',
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/json',
'accept' => 'application/json',
],
]
);
} catch (\Exception $e) {
Log::error($e->getMessage());
return response()->json([
'error' => true,
'msg' => $e->getMessage(),
], $e->getCode() ?: 500);
}
if ($response->getStatusCode() >= 400) {
Log::error('Request could not be made.');
}
return response()->json(
$response->getBody()->getContents(),
$response->getStatusCode()
);
}
I am debugging a class that I use the BaseService in. When I try to use the Guzzle client I receive a Curl exception because it is not creating the uri with the base uri due to it not binding the class.
Log
testing.INFO: In register 1
testing.INFO: In register 2
testing.ERROR: cURL error 6: Could not resolve host: token (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
The host should be https://mybaseuri/token not token. I have logged the api.url config and it returns the correct base uri. I am using Guzzle 6.3.