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

Cloud Core Laravel Package

google/cloud-core

Shared core infrastructure for Google Cloud PHP libraries. Provides common utilities, configuration, retries, transport/auth helpers, and debugging support used across Google Cloud client components. Generally available with stable, backward-compatible releases.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require google/cloud-core
    

    Note: This package is not used directly—it’s a dependency for other Google Cloud PHP libraries (e.g., google/cloud-storage, google/cloud-bigquery). Install the relevant service package instead.

  2. First Use Case: When integrating a Google Cloud service (e.g., Storage, BigQuery), the package handles:

    • Authentication: Automatically detects credentials via GOOGLE_APPLICATION_CREDENTIALS or ADC (Application Default Credentials).
    • Retry Logic: Built-in exponential backoff for transient failures (e.g., rate limits, network issues).
    • Request Validation: Ensures API constraints (e.g., valid query parameters) are met before execution.

    Example (using google/cloud-storage):

    use Google\Cloud\Storage\StorageClient;
    
    $storage = new StorageClient(); // Leverages google/cloud-core for auth/retries
    $bucket = $storage->bucket('my-bucket');
    $objects = $bucket->objects();  // Uses core pagination/streaming
    foreach ($objects as $object) {
        echo $object->name();
    }
    
  3. Where to Look First:

    • Debugging Guide: For logging, environment setup, and emulator support.
    • Service-Specific Docs: Each Google Cloud PHP library (e.g., Storage, BigQuery) builds on google/cloud-core but documents its own API surface.

Implementation Patterns

1. Authentication Workflows

  • Application Default Credentials (ADC): The package auto-detects credentials from:

    • Environment variable: GOOGLE_APPLICATION_CREDENTIALS (path to JSON keyfile).
    • Metadata server (GCE/GKE): Automatically used in cloud environments.
    • Example:
      putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/keyfile.json');
      $client = new Google\Cloud\Storage\StorageClient(); // Uses core auth logic
      
  • Service Account Keyfiles: Deprecated in favor of ADC, but legacy support exists via:

    $client = new Google\Cloud\Storage\StorageClient([
        'keyFile' => '/path/to/keyfile.json', // Deprecated (use ADC instead)
    ]);
    
  • Custom Credentials: For non-Google environments, use the Google\Auth\Credentials class:

    use Google\Auth\Credentials;
    use Google\Auth\ServiceAccountCredentials;
    
    $credentials = ServiceAccountCredentials::fromStream(file_get_contents('keyfile.json'));
    $client = new Google\Cloud\Storage\StorageClient(['credentials' => $credentials]);
    

2. Retry and Error Handling

  • Automatic Retries: Enabled by default for transient errors (e.g., 503 Service Unavailable, 429 Too Many Requests). Customize via:

    $client = new Google\Cloud\Storage\StorageClient([
        'retry' => [
            'max_attempts' => 5,
            'timeout' => 30.0,
        ],
    ]);
    
  • Idempotency: Use Google\Cloud\Core\Idempotency for retry-safe operations (e.g., uploads):

    $uploader = $bucket->upload(
        fopen('file.txt', 'r'),
        ['idempotency' => 'unique-upload-id']
    );
    

3. Options Validation

  • Early Validation: The OptionsValidator trait (added in v1.66.0) validates API constraints before requests:

    $client->bucket('my-bucket')->object('file.txt')->update([
        'metadata' => ['custom' => 'value'], // Validated against API schema
    ]);
    

    Throws Google\Cloud\Core\Exceptions\InvalidArgumentException for invalid options.

  • Custom Validation: Extend Google\Cloud\Core\ApiHelperTrait to add service-specific rules:

    class MyClient extends \Google\Cloud\Core\Client {
        use \Google\Cloud\Core\ApiHelperTrait;
    
        protected function validateOptions(array $options) {
            if (empty($options['required_param'])) {
                throw new \InvalidArgumentException('Missing required parameter');
            }
            return parent::validateOptions($options);
        }
    }
    

4. Streaming and Pagination

  • Lazy-Loading Iterators: Use Google\Cloud\Core\Iterator for efficient pagination:

    foreach ($bucket->objects() as $object) { // Streams objects without loading all at once
        echo $object->name();
    }
    
  • Resumable Uploads: For large files, use the core ResumableUploader:

    $uploader = $bucket->upload(
        fopen('large-file.zip', 'r'),
        ['resumable' => true]
    );
    

5. Environment Awareness

  • Project ID Detection: Use Google\Cloud\Core\DetectProjectIdTrait to auto-detect the project:

    $client = new Google\Cloud\Storage\StorageClient();
    $projectId = $client->detectProjectId(); // Falls back to metadata server
    
  • Emulator Support: Configure local emulators (e.g., Cloud Storage Emulator):

    $client = new Google\Cloud\Storage\StorageClient([
        'projectId' => 'my-project',
        'emulatorHost' => 'http://localhost:4443', // Local emulator
    ]);
    

6. Logging and Debugging

  • Debug Logging: Enable via environment variable:

    export GOOGLE_CLOUD_DEBUG=1
    

    Or programmatically:

    putenv('GOOGLE_CLOUD_DEBUG=1');
    $client = new Google\Cloud\Storage\StorageClient();
    
  • Structured Logging: Integrate with Laravel’s logging:

    use Google\Cloud\Core\DebugLogger;
    
    $logger = new DebugLogger(\Log::channel('google-cloud'));
    $client = new Google\Cloud\Storage\StorageClient(['logger' => $logger]);
    

Gotchas and Tips

Pitfalls

  1. Direct Usage Anti-Pattern:

    • Avoid: Instantiating Google\Cloud\Core\Client directly. This package is a dependency, not an API surface.
    • Do: Use service-specific clients (e.g., Google\Cloud\Storage\StorageClient).
  2. Deprecated keyFile Options:

    • The keyFile and keyFilePath options are deprecated in favor of ADC. Migrate to:
      putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/keyfile.json');
      
    • Error: RuntimeException: keyFile and keyFilePath are deprecated....
  3. Time Zone Handling:

    • The package avoids modifying DateTime objects to preserve timezone consistency. If you need timezone-aware operations, use:
      $dt = new \DateTime('now', new \DateTimeZone('UTC'));
      
  4. PHP 8.4+ Deprecations:

    • The package removes implicit nullables (fixed in v1.62.2). Ensure your code handles nullable types explicitly:
      // Before (may fail in PHP 8.4+):
      $value = $client->someMethod(); // Returns mixed|null
      
      // After:
      if ($value === null) { ... }
      
  5. Emulator Without gRPC:

    • Using the emulator without gRPC support (e.g., REST-only mode) may cause fatal errors. Ensure your emulator is configured for the transport layer you’re using.
  6. Retry Overrides:

    • Custom retry configurations may conflict with service-specific defaults. Test thoroughly in staging:
      // Risky: Overriding retries globally
      $client = new Google\Cloud\Storage\StorageClient([
          'retry' => ['max_attempts' => 1], // Disables retries entirely!
      ]);
      

Debugging Tips

  1. Enable Debug Logging:

    • Set GOOGLE_CLOUD_DEBUG=1 to log HTTP requests/responses:
      export GOOGLE_CLOUD_DEBUG=1
      
    • For Laravel, use:
      putenv('GOOGLE_CLOUD_DEBUG=1');
      
  2. Inspect Requests:

    • Use the Google\Cloud\Core\DebugLogger to capture raw requests:
      $logger = new DebugLogger(function ($message) {
          \Log::debug($message);
      });
      $client = new Google\Cloud\Storage\StorageClient(['logger' => $logger]);
      
  3. Validate Credentials:

    • Test credentials locally with:
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata