Skip to main content
Server SDKs

PHP examples

Provider configuration, request deadlines, and cancellation.

Configure providers​

<?php
require 'sdk/php/autoload.php';

use AffordableGeoApis\GeocodingClient;

$client = new GeocodingClient([
'baseUrl' => getenv('GEOCODING_BASE_URL'),
'apiKey' => getenv('GEOCODING_API_KEY'),
'confidenceThreshold' => 0.8,
'fallbackBudget' => ['maxRequests' => 1000],
'fallbackCircuitBreaker' => ['failureThreshold' => 3, 'cooldownMs' => 30000],
'fallbacks' => [
['provider' => 'google', 'apiKey' => getenv('GOOGLE_MAPS_API_KEY')],
['provider' => 'here', 'apiKey' => getenv('HERE_API_KEY')],
],
]);

$response = $client->geocode([
'street' => '10 Downing Street', 'city' => 'London', 'country' => 'GB',
], ['timeoutMs' => 15000]);

echo $response->provider;
echo json_encode($response, JSON_THROW_ON_ERROR);

GB skips primary and tries backups in order. Read selected raw metadata from $response->providerResponse. It is a stdClass, preserving nested JSON object and array shapes. The first nonempty backup wins; see fallback policy.

Errors and caller deadlines​

use AffordableGeoApis\GeocodingError;
use AffordableGeoApis\RequestCancelledException;
use AffordableGeoApis\RequestTimeoutException;

try {
$response = $client->reverseGeocode(
['lat' => 40.7074, 'lon' => -74.0113],
['timeoutMs' => 15000],
);
if ($response->results === []) {
echo 'No match';
}
} catch (RequestTimeoutException $error) {
echo 'The total provider-chain deadline expired';
} catch (RequestCancelledException $error) {
echo 'Request cancelled';
} catch (GeocodingError $error) {
echo $error->getMessage();
echo $error->errorCode;
echo json_encode($error, JSON_THROW_ON_ERROR);
}

Constructor timeoutMs is a per-provider timeout. Per-call timeoutMs is the total chain deadline. Both use milliseconds. Caller deadline expiry stops the chain; a provider timeout is GeocodingError with errorCode === 'timeout' and may trigger fallback.

Use $error->errorCode for the SDK string code. $error->getCode() is PHP's inherited numeric exception code. Serialized errors use a string code field.

Cancellation​

use AffordableGeoApis\CancellationToken;
use AffordableGeoApis\RequestCancelledException;

$signal = new CancellationToken();
$signal->cancel();
try {
$client->geocode(
['street' => '11 Wall Street', 'city' => 'New York'],
['signal' => $signal],
);
} catch (RequestCancelledException $error) {
echo $error->getMessage();
}

A previously cancelled token prevents provider calls. During a call, the default cURL transport checks the token in its progress callback. Cancellation can be initiated by a signal handler or another Fiber if a custom transport yields; it is cooperative. The SDK includes no async scheduler.

Lifetime and serialization​

Reuse a client to share backup request counts and circuit state. Creating it for every incoming PHP request resets those controls each time. Provider account quotas enforce aggregate limits across PHP workers.

Response, result, attempt, and error objects expose toArray() and implement JsonSerializable. json_encode($response, JSON_THROW_ON_ERROR) handles nested models. Primary responses omit providerResponse when serialized. No client close method is required.

Custom transport​

Pass a transport implementing TransportInterface in constructor options. It must honor timeouts, cancellation, and redirect restrictions. Call RequestContext::check() during processing and use its timeoutMs() method to respect the remaining deadline. See transport reference.

Address autocomplete​

$response = $client->autocomplete(['q' => '11 Wall', 'country' => 'US']);
if ($response->suggestions !== []) {
$address = $client->resolveAutocomplete($response->suggestions[0]);
echo $address->label;
}

Keep the suggestion object, including its provider and Google session token, until selection. See the autocomplete guide.

For a Google-backed typing session, reuse one sessionToken across searches and pass the selected suggestion unchanged to resolution. Generate a new token for the next session. The token is SDK-only; it is not a primary HTTP field. Resolution is a separate provider call, outside fallback budgets/circuit breakers, and returns one address without an envelope or attempt history.