Package · cast

Winter integration

In a Winter application the client is best kept as a bean: the container creates it once per worker, and the pool’s connections live as long as the worker does.

The client as a bean

main/Configuration/HttpConfiguration.php
<?php

declare(strict_types=1);

namespace Main\Configuration;

use Flytachi\Winter\Cast\Client\CastClient;
use Flytachi\Winter\Cast\Client\RetryPolicy;
use Flytachi\Winter\Kernel\App\Attribute\Bean;
use Flytachi\Winter\Kernel\App\Attribute\Configuration;
use Flytachi\Winter\Kernel\App\Attribute\Value;
use Flytachi\Winter\Logger\LoggerFactory;

#[Configuration]
final class HttpConfiguration
{
  #[Bean]
  public function github(#[Value('GITHUB_TOKEN')] string $token): CastClient
  {
      return CastClient::create()
          ->withBaseUrl('https://api.github.com')
          ->withBearerToken($token)
          ->withAccept('application/vnd.github+json')
          ->withUserAgent('my-app/1.0')
          ->withRetry(RetryPolicy::exponential()->withStatuses(502, 503, 504))
          ->withLogger(LoggerFactory::getLogger('github'));
  }
}
main/Services/RepoService.php
use Flytachi\Winter\Cast\Client\CastClient;
use Flytachi\Winter\DI\Attribute\Autowired;

final class RepoService
{
  #[Autowired]
  private CastClient $github;

  public function stars(string $repo): int
  {
      return $this->github->get("repos/{$repo}")->send()->throw()->json()['stargazers_count'];
  }
}

One instance per worker

The client is immutable and keeps no state between requests except the connection pool, and the pool gives every request a connection of its own. So a singleton bean is safe for many coroutines of one Swoole worker.

Several clients

For several APIs, declare several beans with names and inject them by name:

php
#[Configuration]
final class HttpConfiguration
{
  #[Bean(name: 'http.github')]
  public function github(#[Value('GITHUB_TOKEN')] string $token): CastClient
  {
      return CastClient::create()->withBaseUrl('https://api.github.com')->withBearerToken($token);
  }

  #[Bean(name: 'http.stripe')]
  public function stripe(#[Value('STRIPE_KEY')] string $key): CastClient
  {
      return CastClient::create()->withBaseUrl('https://api.stripe.com/v1')->withBasicAuth($key, '');
  }
}
php
use Flytachi\Winter\DI\Attribute\Inject;

final class BillingService
{
  #[Inject('http.stripe')]
  private CastClient $stripe;
}

Two beans of the same type

With two or more CastClient beans, injecting by type (#[Autowired]) becomes an error: the container does not know which one to pick. Name it with #[Inject('…')].

Your own API client

API clients need no base class: a client with an address and a key already is a configured API client. Your own SDK is an ordinary class that receives a CastClient:

php
final class WeatherApi
{
  public function __construct(private CastClient $http) {}

  public static function create(string $key): self
  {
      return new self(CastClient::create()
          ->withBaseUrl('https://api.weather.example/v2')
          ->withHeader('X-Api-Key', $key));
  }

  /** @return array<string, mixed> */
  public function today(string $city): array
  {
      return $this->http->get('today', ['city' => $city])->send()->throw()->jsonOrFail();
  }
}

This gives as many instances with different keys as you like, a client that is replaced in tests through withTransport(), and no shared parent whose changes would break every SDK.

Logs

php
$client->withLogger(LoggerFactory::getLogger('github'));
text
[DEBUG] (github): GET https://api.github.com/repos/flytachi/winter-cast → 200 (184 ms)
[WARNING] (github): GET https://api.github.com/search/code attempt 1 failed (HTTP 503), retrying in 512 ms
[DEBUG] (github): GET https://api.github.com/search/code → 200 (1204 ms, 2 attempts)
[ERROR] (github): GET https://api.github.com/user failed after 3 attempt(s): … Could not connect to server
Level When
debug one line per request: method, address, status, time, attempts, redirects
warning every retry: attempt number, reason, pause
error a failure after all attempts

Headers, bodies and query strings never reach the log, so keys in the address do not leak. The client fills in the placeholders itself, so lines are complete with any PSR-3 logger. For a format of your own, see Your own log format.

The facade in an application

If your code uses the Cast facade, give it a client once at application start:

php
Cast::setClient(CastClient::create()->withUserAgent('my-app/1.0')->withTimeout(10));

Injecting a CastClient bean is still preferable: the settings are visible where the client is created, and it is replaced in tests.