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**:
   ```bash
   composer require google/gax

Requires PHP 8.1+ and ext-protobuf (install via pecl install protobuf).

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

  2. Key Entry Points:

    • GapicClientTrait: Core client logic (e.g., middleware, options).
    • ApiException: Standardized error handling.
    • ClientOptionsTrait: Configure clients (e.g., credentials, timeouts).

Implementation Patterns

1. Middleware Integration

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());

2. Streaming Responses

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
}

3. Customizing Client Options

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);

4. Error Handling

Catch ApiException for Google API errors:

try {
    $client->callApi();
} catch (ApiException $e) {
    $errorDetails = $e->getErrorDetails(); // Structured error data
    \Log::error($e->getMessage(), $errorDetails);
}

5. Emulator Support

Use InsecureCredentialsWrapper for local testing:

$options = (new ClientOptions())
    ->setCredentials(new InsecureCredentialsWrapper());

$client = new MyServiceClient($options);

Gotchas and Tips

Pitfalls

  1. Protobuf Compatibility:

    • Ensure google/protobuf is v5+ (see #661).
    • Use RepeatedField from Google\Protobuf\Internal\RepeatedField (namespace changed in v5).
  2. Middleware Order:

    • Middleware runs top-to-bottom (first added = first executed).
    • Use prependMiddleware() for early-stage processing (e.g., auth).
  3. Streaming Quirks:

    • Bidi streams require rpcName in the opening request (added in v1.38.0).
    • Always consume streams fully to avoid resource leaks.
  4. Credentials:

    • InsecureCredentialsWrapper returns null for auth headers in some cases (fixed in v1.29.1).
    • Environment variables (e.g., GOOGLE_CLOUD_UNIVERSE_DOMAIN) override defaults.
  5. Deprecations:

    • ApiException::__toString() was overridden incorrectly (fixed in v1.38.2). Prefer getMessage().

Debugging Tips

  • Enable Logging: Add transport logging via ClientOptions:
    $options->setTransportOptions([
        'logging' => [
            'level' => \Psr\Log\LogLevel::DEBUG,
        ],
    ]);
    
  • Inspect Middleware: Use dd($client->getMiddleware()) to debug the call stack.
  • Protobuf Serialization: For custom types, extend Serializer or use JsonSerializer as a fallback.

Extension Points

  1. Custom Serializers: Register a custom encoder in Serializer:
    $serializer = new Serializer();
    $serializer->registerEncoder('custom_type', function ($value) {
        return json_encode($value);
    });
    
  2. Transport Middleware: Implement TransportCallMiddleware for low-level gRPC/HTTP hooks (added in v1.40.0).
  3. Client Options: Extend 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;
        }
    }
    

Laravel-Specific Tips

  • Service Providers: Bind clients as singletons with shared options:
    $this->app->singleton(MyServiceClient::class, function ($app) {
        return new MyServiceClient(
            (new ClientOptions())
                ->setCredentials($app['auth.credentials'])
        );
    });
    
  • Configuration: Use Laravel’s config to manage credentials/options:
    $options = (new ClientOptions())
        ->setCredentials(Credentials::fromServiceAccount(
            config('services.google.key_file')
        ));
    
  • Exception Handling: Convert ApiException to Laravel’s HttpException:
    catch (ApiException $e) {
        throw new HttpException(
            $e->getCode(),
            $e->getMessage(),
            $e->getErrorDetails()
        );
    }
    

---
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope