google/gax
Google API Core for PHP (gax-php) provides shared components used by generated Google Cloud API clients, including gRPC-based call handling, retries, timeouts, and page streaming. Designed for PHP 8.1+ and Google API conventions; most users won’t call it directly.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require google/gax
Requires PHP 8.1+ and ext-protobuf (install via pecl install protobuf).
First Use Case:
Use with Google Cloud client libraries (e.g., google/cloud-*). Example with Firestore:
use Google\Cloud\Firestore\FirestoreClient;
$firestore = new FirestoreClient();
$doc = $firestore->collection('users')->document('alice')->snapshot();
The package handles retry logic, streaming, and authentication under the hood.
Key Entry Points:
GapicClientTrait: Core client logic (e.g., middleware, options).ApiException: Standardized error handling.ClientOptionsTrait: Configure clients (e.g., credentials, timeouts).Extend client behavior via middleware (e.g., logging, metrics):
use Google\ApiCore\ApiCoreClientInterface;
use Google\ApiCore\Middleware\MiddlewareInterface;
class LoggingMiddleware implements MiddlewareInterface {
public function handle($request, callable $next) {
\Log::debug('Request:', $request);
return $next($request);
}
}
// Apply to a client:
$client->prependMiddleware(new LoggingMiddleware());
Handle paginated/streaming responses (e.g., list operations):
use Google\ApiCore\ApiCoreClientInterface;
$client = new MyServiceClient();
$stream = $client->listResources();
foreach ($stream as $resource) {
// Process each item
}
Configure retries, timeouts, or credentials:
use Google\ApiCore\ClientOptionsTrait;
use Google\Auth\Credentials;
$options = (new ClientOptions())
->setCredentials(Credentials::fromServiceAccountFile('path/to/key.json'))
->setRetrySettings([
'maxAttempts' => 3,
'initialBackoff' => 100,
]);
$client = new MyServiceClient($options);
Catch ApiException for Google API errors:
try {
$client->callApi();
} catch (ApiException $e) {
$errorDetails = $e->getErrorDetails(); // Structured error data
\Log::error($e->getMessage(), $errorDetails);
}
Use InsecureCredentialsWrapper for local testing:
$options = (new ClientOptions())
->setCredentials(new InsecureCredentialsWrapper());
$client = new MyServiceClient($options);
Protobuf Compatibility:
google/protobuf is v5+ (see #661).RepeatedField from Google\Protobuf\Internal\RepeatedField (namespace changed in v5).Middleware Order:
prependMiddleware() for early-stage processing (e.g., auth).Streaming Quirks:
rpcName in the opening request (added in v1.38.0).Credentials:
InsecureCredentialsWrapper returns null for auth headers in some cases (fixed in v1.29.1).GOOGLE_CLOUD_UNIVERSE_DOMAIN) override defaults.Deprecations:
ApiException::__toString() was overridden incorrectly (fixed in v1.38.2). Prefer getMessage().ClientOptions:
$options->setTransportOptions([
'logging' => [
'level' => \Psr\Log\LogLevel::DEBUG,
],
]);
dd($client->getMiddleware()) to debug the call stack.Serializer or use JsonSerializer as a fallback.Serializer:
$serializer = new Serializer();
$serializer->registerEncoder('custom_type', function ($value) {
return json_encode($value);
});
TransportCallMiddleware for low-level gRPC/HTTP hooks (added in v1.40.0).ClientOptions to add project-specific settings:
class MyClientOptions extends ClientOptions {
private ?string $customSetting = null;
public function setCustomSetting(string $value): self {
$this->customSetting = $value;
return $this;
}
}
$this->app->singleton(MyServiceClient::class, function ($app) {
return new MyServiceClient(
(new ClientOptions())
->setCredentials($app['auth.credentials'])
);
});
$options = (new ClientOptions())
->setCredentials(Credentials::fromServiceAccount(
config('services.google.key_file')
));
ApiException to Laravel’s HttpException:
catch (ApiException $e) {
throw new HttpException(
$e->getCode(),
$e->getMessage(),
$e->getErrorDetails()
);
}
---
How can I help you explore Laravel packages today?