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 Common Protos Laravel Package

google/cloud-common-protos

Generated PHP Protocol Buffer classes shared across Google Cloud APIs (part of google-cloud-php). Install via Composer as google/cloud-common-protos to use stable, Apache-2.0 licensed common proto message types in your apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require google/cloud-common-protos
    

    Ensure your environment supports the google/protobuf PHP extension (required for protobuf serialization).

  2. First Use Case: Audit Logs Use the Google\Cloud\Core\V1\AuditLog class to structure log entries for Google Cloud Audit Logs:

    use Google\Cloud\Core\V1\AuditLog;
    use Google\Cloud\Core\V1\LogEntry;
    
    $logEntry = new LogEntry();
    $logEntry->setTimestamp(new \Google\Type\Timestamp());
    $logEntry->setProtoPayload(new AuditLog());
    
    // Populate AuditLog fields (e.g., authentication, methodName, etc.)
    
  3. Key Classes to Explore

    • Google\Cloud\Core\V1\AuditLog: For audit logging compliance.
    • Google\Rpc\Status: Standardize error responses.
    • Google\Logging\Type\HttpRequest: Enrich logs with HTTP metadata.
    • Google\Protobuf\Internal\Message: Base class for protobuf messages.
  4. Where to Look First

    • Documentation: Google Cloud PHP Docs (primary source).
    • Generated Classes: Browse the source code for available protobuf types.
    • Laravel Integration: Use the package indirectly via Google Cloud SDKs (e.g., google/cloud-logging).

Implementation Patterns

Usage Patterns

  1. Indirect Usage via Google Cloud SDKs Most Laravel developers will use this package indirectly through Google Cloud SDKs (e.g., google/cloud-logging). Example:

    use Google\Cloud\Logging\V2\LoggingClient;
    
    $logging = new LoggingClient();
    $logName = $logging->logName('your-project-id', 'your-log');
    $entry = $logging->entry($logName, [
        'severity' => 'INFO',
        'message' => 'Test log entry',
        'httpRequest' => (new \Google\Logging\Type\HttpRequest())
            ->setRequestUrl('https://example.com')
            ->setRequestMethod('GET')
    ]);
    $logging->write($entry);
    

    The SDK handles protobuf serialization under the hood.

  2. Direct Protobuf Usage For custom gRPC services or advanced integrations, use generated protobuf classes directly:

    use Google\Protobuf\Internal\Message;
    use Google\Cloud\Core\V1\AuditLog;
    
    $auditLog = new AuditLog();
    $auditLog->setAuthenticationInfo('user@example.com');
    $auditLog->setMethodName('/api/v1/resource');
    
    // Serialize to binary protobuf format
    $binaryData = $auditLog->serializeToString();
    
  3. Laravel Service Container Integration Bind protobuf clients to Laravel’s container for dependency injection:

    $this->app->bind(LoggingClient::class, function ($app) {
        return new LoggingClient([
            'keyFilePath' => storage_path('service-account.json'),
        ]);
    });
    
  4. Protobuf Message Extension Extend protobuf messages to add custom fields while maintaining compatibility:

    use Google\Logging\Type\LogEntry;
    
    class CustomLogEntry extends LogEntry {
        public function setCustomField($value) {
            $this->customField = $value;
        }
    }
    

Workflows

  1. Audit Logging Workflow

    • Use AuditLog to structure log entries for Google Cloud Audit Logs.
    • Integrate with Laravel’s logging system via a custom handler:
      $logger = new \Monolog\Logger('google');
      $logger->pushHandler(new GoogleCloudLogHandler($loggingClient));
      
  2. Error Standardization

    • Standardize API errors using Google\Rpc\Status:
      $status = new \Google\Rpc\Status();
      $status->setCode(\Google\Rpc\Code::INVALID_ARGUMENT);
      $status->setMessage('Invalid input data');
      throw new \Google\ApiCore\ApiException($status);
      
  3. HTTP Metadata Enrichment

    • Attach HTTP request metadata to logs for observability:
      $httpRequest = new \Google\Logging\Type\HttpRequest();
      $httpRequest->setRequestUrl(request()->fullUrl());
      $httpRequest->setRequestMethod(request()->method());
      $logEntry->setHttpRequest($httpRequest);
      

Integration Tips

  1. Environment Setup

    • Ensure the google/protobuf extension is enabled in php.ini:
      extension=protobuf.so
      
    • For Docker, include in your Dockerfile:
      RUN docker-php-ext-install protobuf
      
  2. Laravel Logging

    • Create a custom Monolog handler to forward logs to Google Cloud Logging:
      class GoogleCloudLogHandler extends \Monolog\Handler\AbstractProcessingHandler {
          public function __construct(LoggingClient $loggingClient) {
              parent::__construct(Monolog\Logger::DEBUG, true);
              $this->loggingClient = $loggingClient;
          }
      
          protected function write(array $record): void {
              $logEntry = $this->loggingClient->entry(...);
              $this->loggingClient->write($logEntry);
          }
      }
      
  3. Protobuf Schema Evolution

    • Monitor Google’s protobuf schema updates (e.g., googleapis/googleapis) to handle breaking changes proactively.
    • Use versioned dependencies (e.g., ^1.0) to stay aligned with Google’s releases.
  4. Testing

    • Mock protobuf messages in unit tests:
      $mockAuditLog = $this->createMock(AuditLog::class);
      $mockAuditLog->method('serializeToString')->willReturn('mocked-data');
      

Gotchas and Tips

Pitfalls

  1. Extension Dependency

    • Issue: The google/protobuf PHP extension is required but not always enabled by default.
    • Fix: Explicitly enable the extension in your environment or Docker setup. Check for errors like:
      Fatal error: Uncaught Error: Class 'Google\Protobuf\Internal\Message' not found
      
    • Workaround: Use a Docker image with protobuf pre-installed (e.g., google/cloud-sdk).
  2. Immutable DTOs

    • Issue: Protobuf messages are immutable; modifying fields requires creating new instances.
    • Fix: Use builder patterns or helper methods:
      $updatedLog = $logEntry->withCustomField('new-value');
      
  3. Schema Versioning

    • Issue: Protobuf schemas evolve, and breaking changes may occur (e.g., deprecated fields like ReservationResourceUsage).
    • Fix: Pin to specific versions or use Google’s SDKs, which handle schema evolution internally.
  4. Binary Data Handling

    • Issue: Protobuf messages serialize to binary format, which may not be JSON-serializable.
    • Fix: Use serializeToString() for binary data or toArray() for debug-friendly output (if available).
  5. Laravel Serialization

    • Issue: Protobuf objects may not serialize/deserialize cleanly with Laravel’s JSON middleware.
    • Fix: Exclude protobuf objects from JSON serialization or implement custom serializers:
      $response->setData([
          'log_entry' => $logEntry->serializeToString(), // Binary data
      ]);
      
  6. Performance Overhead

    • Issue: Protobuf serialization/deserialization can be slower than JSON for small payloads.
    • Fix: Benchmark and use JSON for lightweight integrations; reserve protobuf for high-performance or gRPC use cases.

Debugging

  1. Inspect Protobuf Messages

    • Use var_dump($message->serializeToString(), true) to inspect binary data.
    • For human-readable output, use tools like protobuf-inspector.
  2. Common Errors

    • Class not found: Ensure google/cloud-common-protos and google/protobuf are installed.
    • Method not found: Verify the protobuf class version matches your Google Cloud SDK version.
    • Serialization errors: Check for deprecated or required fields in the schema.
  3. Logging Protobuf Data

    • Log protobuf messages as binary data or convert to JSON for debugging:
      \Log::debug('Protobuf data', [
          'binary' => $message->serializeToString(),
          'json' => json_encode($message->toArray()), // If supported
      ]);
      

Tips

  1. Leverage Google Cloud SDKs
    • Prefer using SDKs like google/cloud-logging over direct protobuf usage to avoid reinventing serialization logic.
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