Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Gax Laravel Package

google/gax

Google API Core for PHP (gax-php) provides shared infrastructure for Google API clients, especially generated libraries using gRPC. Includes helpers for retries, pagination/page streaming, long-running operations, and Google API conventions. Requires PHP 8.1+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require google/gax
    

    Requires PHP 8.1+ and pecl install protobuf.

  2. First Use Case: Integrate with a Google API client (e.g., Cloud Storage, Pub/Sub) that uses google/gax under the hood. Example:

    use Google\Cloud\Storage\StorageClient;
    
    $storage = new StorageClient();
    $buckets = $storage->buckets(); // Leverages gax for pagination/retry
    
  3. Key Entry Points:

    • GapicClientTrait: Auto-injected into generated clients (e.g., StorageClient).
    • Retry/Backoff: Configured via RetrySettings or ExponentialBackoff.
    • Streaming: Use PageStream for paginated responses or BidiStream for bidirectional streams.

Implementation Patterns

1. Client Configuration

Use ClientOptionsTrait to customize clients:

use Google\ApiCore\ClientOptionsTrait;

class CustomClient {
    use ClientOptionsTrait;

    public function __construct() {
        $this->clientOptions = [
            'apiKey' => 'YOUR_API_KEY',
            'universeDomain' => 'googleapis.com', // For multi-tenant environments
        ];
    }
}

2. Middleware Stack

Extend functionality with middleware (e.g., logging, metrics):

use Google\ApiCore\ApiMiddleware;
use Google\ApiCore\Middleware\TransportCallMiddleware;

$client = new StorageClient();
$client->prependMiddleware(new TransportCallMiddleware(function ($call) {
    // Log request/response
    return $call->proceed();
}));

3. Retry Policies

Configure retries for transient failures:

use Google\ApiCore\Retry\RetrySettings;

$retrySettings = new RetrySettings([
    'maxAttempts' => 3,
    'initialBackoff' => 100, // ms
    'maxBackoff' => 5000,   // ms
]);
$client->setRetrySettings($retrySettings);

4. Streaming Responses

Handle paginated or bidirectional streams:

// Paginated response (e.g., list buckets)
foreach ($client->buckets()->list() as $bucket) {
    // Process each bucket
}

// Bidirectional stream (e.g., Pub/Sub)
$stream = $client->subscribe($topic);
$stream->onMessage(function ($message) {
    // Handle message
});

5. Error Handling

Access detailed error info:

try {
    $client->deleteBucket('bucket-name');
} catch (ApiException $e) {
    $errorDetails = $e->getErrorDetails(); // Structured error metadata
    $statusCode = $e->getStatus()->getCode();
}

Gotchas and Tips

Common Pitfalls

  1. Middleware Order:

    • Middleware runs in LIFO order (last added = first executed). Use prependMiddleware() for early-stage processing (e.g., auth).
  2. Universe Domain:

    • If using multi-tenant environments (e.g., GCP vs. Anthos), explicitly set universeDomain in ClientOptions to avoid misrouted requests.
  3. Protobuf Serialization:

    • Custom protobuf types may require explicit registration in the Serializer. Use Serializer::register() for non-standard types.
  4. Emulator Support:

    • For local testing, use InsecureCredentialsWrapper or InsecureRequestBuilder to bypass TLS:
      $client->setCredentialsWrapper(new InsecureCredentialsWrapper());
      
  5. Deprecated Methods:

    • Avoid GapicClientTrait::modifyClientOptions() in newer versions; use ClientOptionsTrait instead.

Debugging Tips

  • Enable Logging: Add a middleware to log requests/responses:

    $client->prependMiddleware(new ApiMiddleware(function ($call) {
        error_log('Request: ' . print_r($call->getRequest(), true));
        return $call->proceed();
    }));
    
  • Retry Debugging: Set RetrySettings with maxAttempts: 1 to test failure paths:

    $retrySettings = new RetrySettings(['maxAttempts' => 1]);
    $client->setRetrySettings($retrySettings);
    
  • Protobuf Validation: Use google/protobuf's built-in validation:

    $request = new MyRequest();
    $request->setField('value');
    if (!$request->isInitialized()) {
        throw new \RuntimeException('Invalid protobuf request');
    }
    

Extension Points

  1. Custom Transports: Implement TransportInterface for non-gRPC backends (e.g., REST):

    use Google\ApiCore\Transport\TransportInterface;
    
    class CustomTransport implements TransportInterface {
        public function call($request, $metadata = []) {
            // Implement custom logic
        }
    }
    
  2. Serializer Extensions: Extend Serializer for custom protobuf types:

    use Google\ApiCore\Serializer;
    
    Serializer::register('MyCustomType', function ($value) {
        return new MyCustomType($value);
    });
    
  3. API Key Rotation: Dynamically update apiKey in ClientOptions without recreating the client:

    $client->setClientOptions(['apiKey' => 'NEW_API_KEY']);
    

Configuration Quirks

  • Environment Variables: universeDomain can be set via GAX_UNIVERSE_DOMAIN env var (fallback: googleapis.com).
  • Default Auth: If no credentials are set, the library defaults to no authentication (not anonymous). Explicitly set CredentialsWrapper to avoid surprises.
  • Backward Compatibility: Methods like GapicClientTrait::modifyClientOptions() are deprecated in favor of ClientOptionsTrait::setClientOptions().

Performance

  • Caching: The Serializer caches compiled protobuf schemas. For high-throughput apps, preload schemas during bootstrap:
    $serializer = new Serializer();
    $serializer->compileSchema(file_get_contents('schema.proto'));
    
  • Streaming: Use PageStream::limit() to avoid memory issues with large datasets:
    $stream = $client->listObjects($bucket)->limit(1000);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport