PHP code example of valencio / laravel-toolkit

1. Go to this page and download the library: Download valencio/laravel-toolkit 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/ */

    

valencio / laravel-toolkit example snippets


use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Valencio\LaravelToolkit\Integration\HttpClient;
use Valencio\LaravelToolkit\Integration\IntegrationResult;

final class ExampleClient extends HttpClient
{
    protected ?string $serviceConfigKey = 'services.example';

    private string $baseUrl;
    private string $token;

    public function __construct(...)
    {
        parent::__construct(...);
        $this->baseUrl = (string) ($this->settings['base_url'] ?? '');
        $this->token = (string) ($this->settings['token'] ?? '');
    }

    protected function configureRequest(PendingRequest $request): PendingRequest
    {
        return $request
            ->baseUrl($this->baseUrl)
            ->withToken($this->token);
    }

    /** 默认软失败:返回 Result,不中断调用栈 */
    public function fetchItems(array $query = []): IntegrationResult
    {
        return $this->get('/items', [
            'query' => $query,
        ], 'fetch_items');
    }

    /** 硬失败:失败直接抛 IntegrationException */
    public function fetchItemsOrFail(array $query = []): Response
    {
        return $this->getOrFail('/items', [
            'query' => $query,
        ], 'fetch_items');
    }
}

$result = $client->fetchItems(['page' => 1]);

// 软失败:拿不到就空数组,接口仍可继续
$items = $result->failed()
    ? []
    : ($result->response()?->json('data') ?? []);

// 硬失败:必须成功(IntegrationException 实现 ShouldntReport,避免与集成日志重复、泄密)
$response = $client->fetchItemsOrFail();