PHP code example of usamamuneerchaudhary / laraclient

1. Go to this page and download the library: Download usamamuneerchaudhary/laraclient library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

usamamuneerchaudhary / laraclient example snippets


use Usamamuneerchaudhary\LaraClient\Facades\LaraClient;

$weather = LaraClient::connection('weatherapi')->get('current.json', ['q' => 'london']);
$countries = LaraClient::connection('geodb')->get('countries');

$weather->json('current.temp_c');

'defaults' => [
    'timeout' => 30,
    'retry' => ['enabled' => true, 'times' => 3],
    'circuit_breaker' => ['enabled' => true],
],

'connections' => [

    'github' => [
        'base_uri' => 'https://api.github.com/',
        'auth' => ['driver' => 'bearer', 'token' => env('GITHUB_TOKEN')],
        'pagination' => ['strategy' => 'link_header'],
    ],

    'weatherapi' => [
        'base_uri' => 'https://weatherapi-com.p.rapidapi.com/',
        'auth' => ['driver' => 'header', 'name' => 'X-RapidAPI-Key', 'value' => env('RAPIDAPI_KEY')],
        'cache' => ['enabled' => true, 'ttl' => 600],
    ],

    'salesforce' => [
        'base_uri' => env('SALESFORCE_BASE_URI'),
        'auth' => [
            'driver' => 'oauth2',
            'token_url' => env('SALESFORCE_TOKEN_URL'),
            'client_id' => env('SALESFORCE_CLIENT_ID'),
            'client_secret' => env('SALESFORCE_CLIENT_SECRET'),
        ],
        'rate_limit' => ['enabled' => true, 'limit' => 100, 'window' => 60],
    ],
],

use Usamamuneerchaudhary\LaraClient\Auth\AuthFactory;

AuthFactory::extend('hmac', fn (array $config) => new HmacAuth($config['secret']));

LaraClient::connection('github')->get('users/{username}/repos', [
    'username' => 'usamamuneerchaudhary',   // fills the path placeholder
    'sort' => 'updated',                    // left over, so it becomes a query parameter
]);

LaraClient::connection('stripe')
    ->withHeader('Stripe-Version', '2024-06-20')
    ->timeout(5)
    ->retry(times: 4, baseDelayMs: 250)
    ->idempotent($job->uuid)
    ->throwOnError()
    ->post('charges', ['amount' => 500, 'currency' => 'gbp']);

$response->json();                  // whole payload as an array
$response->json('data.0.email');    // dot-addressed
$response->collect('data');         // Illuminate Collection
$response->object();
$response->body();

$response->ok();  $response->successful();  $response->failed();
$response->clientError();  $response->serverError();
$response->notFound();  $response->unauthorized();  $response->tooManyRequests();

$response->header('X-Request-Id');
$response->fromCache();
$response->durationMs();

$response->throw();                       // RequestException on 4xx/5xx
$response->onError(fn ($r) => report($r->json('error.message')));

'retry' => [
    'times' => 3,
    'base_delay' => 200,   // 200ms -> 400ms -> 800ms, randomised
    'jitter' => true,
    'statuses' => [408, 425, 429, 500, 502, 503, 504],
    'methods' => ['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS'],
],

public function handle(): void
{
    try {
        LaraClient::connection('salesforce')->get('accounts');
    } catch (RateLimitExceededException $e) {
        $this->release($e->retryAfter);
    }
}

'circuit_breaker' => ['enabled' => true, 'failure_threshold' => 5, 'cooldown' => 60],

LaraClient::connection('weatherapi')->cacheFor(600)->get('current.json', ['q' => 'london']);

Cache::tags('laraclient:weatherapi')->flush();

use Usamamuneerchaudhary\LaraClient\Pool;

$results = LaraClient::connection('github')->pool(fn (Pool $pool) => [
    $pool->as('user')->get('user'),
    $pool->as('repos')->get('user/repos'),
    $pool->as('orgs')->get('user/orgs'),
]);

$results['user']->json('login');

LaraClient::connection('github')
    ->paginate('user/repos')
    ->each(fn (array $repo) => Repo::sync($repo));

LaraClient::fake([
    'github/user*' => LaraClient::response(['login' => 'usama']),
    'stripe/*'     => LaraClient::response(['error' => 'card_declined'], 402),
    '*'            => LaraClient::response([], 404),
]);

$this->post('/sync');

LaraClient::assertSentCount(1);
LaraClient::assertSent(fn ($request) => $request->isPost()
    && $request->urlIs('*charges')
    && $request->json('amount') === 500);

LaraClient::fake(['*' => [
    LaraClient::response([], 503),
    LaraClient::response(['ok' => true]),
]]);

// AppServiceProvider::boot()
Gate::define('viewLaraClient', fn ($user) => $user->isAdmin());

// config/lara_client.php
'dashboard' => [
    'middleware' => ['web', 'auth'], // or Filament, Sanctum, etc.
],

use Usamamuneerchaudhary\LaraClient\Events\{RequestSending, ResponseReceived, RequestFailed};

LaraClient::beforeSending(function ($request, $method, $url, &$options) {
    $options['headers']['X-Request-Id'] = (string) Str::uuid();
});

LaraClient::afterResponse(fn ($response) => Log::debug($response->durationMs()));

class GithubClient
{
    /**
     * Fetch a single part of a widget
     *
     * @param  int  $widgetId  Numeric widget id
     */
    public function getWidgetPart(int $widgetId, string $partId, array $query = []): Response
    {
        return $this->request()->get('widgets/{widgetId}/parts/{partId}', [
            'widgetId' => $widgetId, 'partId' => $partId,
        ] + $query);
    }
}

$client->using(fn ($r) => $r->timeout(2)->cacheFor(300))->listWidgets();

'redact' => [
    'headers' => ['authorization', 'x-api-key', 'x-signature'],
    'body' => ['password', 'client_secret', 'card_number', 'national_id'],
],
bash
composer vendor:publish --tag=laraclient-config
php artisan migrate
bash
LARACLIENT_RECORDER=record php artisan test --filter=GithubTest   # captures fixtures
LARACLIENT_RECORDER=replay php artisan test                       # hermetic, no network
bash
php artisan laraclient:check              # ping every connection; fails the build on a bad credential
php artisan laraclient:prune              # trim the logs table (schedule this daily)
php artisan laraclient:make github --spec=openapi.json