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 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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require google/gax
    

    Requires PHP 8.1+ and protobuf extension.

  2. First Use Case: Basic API Client Most Laravel developers will interact with gax-php indirectly via Google Cloud client libraries (e.g., google/cloud-storage). However, for direct use:

    use Google\ApiCore\ApiException;
    use Google\ApiCore\Gapic\GapicClientTrait;
    use Google\ApiCore\Gapic\Rest\RestClient;
    
    class MyClient extends RestClient {
        use GapicClientTrait;
    
        protected function modifyClientOptions(): void {
            $this->clientOptions->setApiKey('YOUR_API_KEY');
        }
    }
    
  3. Key Entry Points

    • GapicClientTrait: Core trait for Google API clients (retry, pagination, auth).
    • ApiException: Standardized error handling for Google API errors.
    • Middleware: Extend request/response behavior (e.g., logging, metrics).

Implementation Patterns

1. Client Configuration

Workflow: Configure clients with environment-aware defaults.

// config/google.php
return [
    'client_options' => [
        'api_key' => env('GOOGLE_API_KEY'),
        'universe_domain' => env('GOOGLE_UNIVERSE_DOMAIN', 'googleapis.com'),
    ],
];

// In your service
$client = new MyClient([
    'clientOptions' => config('google.client_options'),
]);

2. Middleware Integration

Pattern: Extend request/response pipelines (e.g., add headers, logging).

use Google\ApiCore\Gapic\Middleware\MiddlewareInterface;

class LoggingMiddleware implements MiddlewareInterface {
    public function handle($request, callable $next) {
        Log::debug('Outgoing request:', $request->getData());
        return $next($request);
    }
}

// Register in client
$client->prependMiddleware(new LoggingMiddleware());

3. Pagination & Streaming

Use Case: Handle large datasets efficiently.

// Paginated list (auto-handled by GapicClientTrait)
$results = $client->listObjects(['pageSize' => 100]);
foreach ($results as $page) {
    foreach ($page->getItems() as $item) {
        // Process item
    }
}

// Bidirectional streaming (e.g., Pub/Sub)
$stream = $client->streamingCall(['callback' => fn($response) => Log::info($response)]);

4. Error Handling

Pattern: Leverage ApiException for structured errors.

try {
    $client->callApi();
} catch (ApiException $e) {
    $errorDetails = $e->getErrorDetails(); // Structured error metadata
    Log::error('Google API Error:', $errorDetails);
    throw new \RuntimeException('Failed to call API', 0, $e);
}

5. Testing

Pattern: Use emulators for local development.

// Configure emulator in tests
$client = new MyClient([
    'clientOptions' => [
        'hasEmulator' => true,
    ],
]);

Gotchas and Tips

Pitfalls

  1. Middleware Order Matters

    • prependMiddleware() adds middleware before existing middleware. Use appendMiddleware() for post-processing.
    • Debug Tip: Log middleware stack order during development.
  2. Protobuf Version Conflicts

    • Ensure google/protobuf is pinned to ^5.0 (gax-php requires v5+).
    • Fix: Update composer.json and run composer update google/protobuf.
  3. Universe Domain Misconfiguration

    • Defaults to googleapis.com. Override via clientOptions or env var GOOGLE_UNIVERSE_DOMAIN.
    • Common Issue: API calls fail silently in GCP environments if misconfigured.
  4. Emulator-Specific Quirks

    • InsecureCredentialsWrapper bypasses auth. Never use in production.
    • Tip: Use hasEmulator: true in clientOptions for local testing.
  5. Deprecated Methods

    • Avoid GapicClientTrait::setApiKey() (use modifyClientOptions() instead).
    • Check: Run phpstan to catch deprecated calls.

Debugging Tips

  • Enable Debug Logging
    $client->getOptions()->setLoggingOptions([
        'logLevel' => \Google\ApiCore\LoggingOptions::LOG_LEVEL_DEBUG,
    ]);
    
  • Inspect Raw Requests Use TransportCallMiddleware to log gRPC/REST payloads:
    $client->prependMiddleware(new class implements MiddlewareInterface {
        public function handle($request, callable $next) {
            Log::debug('Raw request:', [
                'method' => $request->getMethod(),
                'data' => $request->getData(),
            ]);
            return $next($request);
        }
    });
    

Extension Points

  1. Custom Serialization Override Serializer for non-standard protobuf types:

    use Google\ApiCore\Serializer;
    
    class CustomSerializer extends Serializer {
        protected function encodeCustomType($value): string {
            // Custom logic
        }
    }
    
  2. Transport-Specific Logic Extend TransportOptions for custom HTTP/gRPC behavior:

    $client->getOptions()->setTransportOptions([
        'grpc' => [
            'timeout' => 30.0, // Custom timeout
        ],
    ]);
    
  3. Operation Polling For long-running operations, use OperationResponse:

    $operation = $client->startOperation(['request' => $data]);
    $response = $operation->waitUntilComplete();
    

Laravel-Specific Tips

  • Service Container Binding Bind clients as singletons in AppServiceProvider:
    $this->app->singleton(MyClient::class, fn($app) => new MyClient([
        'clientOptions' => $app['config']['google.client_options'],
    ]));
    
  • Environment Variables Use Laravel’s .env for sensitive config:
    GOOGLE_API_KEY=your_key_here
    GOOGLE_UNIVERSE_DOMAIN=googleapis.com
    
  • Queue Jobs for Async Calls Offload long-running operations to queues:
    dispatch(new ProcessGoogleOperation($client, $request));
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity