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. Install the Package Add to composer.json:

    "require": {
        "google/cloud-common-protos": "^1.0"
    }
    

    Run composer install.

  2. Verify Installation Check autoloaded classes:

    composer dump-autoload
    

    Verify the Google\Protobuf namespace is available.

  3. First Use Case: Audit Logs Use the Google\Protobuf\Internal\Message base class to create a custom audit log entry:

    use Google\Protobuf\Internal\Message;
    use Google\Cloud\CommonProtos\AuditLog;
    
    $logEntry = new AuditLog\LogEntry();
    $logEntry->setTimestamp(new \Google\Type\Timestamp());
    $logEntry->getTimestamp()->setSeconds(time());
    

Where to Look First

  • Generated Classes: Browse the Google Cloud PHP GitHub for protobuf definitions (e.g., AuditLog, Status, HttpRequest).
  • Laravel Integration: Use the package indirectly via Google Cloud SDKs (e.g., google/cloud-logging) to avoid manual protobuf handling.
  • Protobuf Docs: Refer to Google’s Protobuf Guide for schema design best practices.

Implementation Patterns

Usage Patterns

  1. Indirect Usage via Google Cloud SDKs Most Laravel developers will use this package indirectly through SDKs like google/cloud-logging:

    use Google\Cloud\Logging\LoggingClient;
    
    $logging = new LoggingClient();
    $entry = $logging->entry('my-log', [
        'severity' => 'INFO',
        'textPayload' => 'Test log entry'
    ]);
    $logging->write($entry);
    

    Under the hood, this uses google/cloud-common-protos for protobuf serialization.

  2. Direct Protobuf Manipulation For custom gRPC services or advanced integrations, instantiate protobuf messages:

    use Google\Cloud\CommonProtos\AuditLog\LogEntry;
    use Google\Type\Timestamp;
    
    $logEntry = new LogEntry();
    $logEntry->setTimestamp(new Timestamp());
    $logEntry->getTimestamp()->setSeconds(time());
    $logEntry->setProtoPayload(file_get_contents('custom.proto'));
    
  3. Laravel Service Container Integration Bind protobuf clients to Laravel’s container for dependency injection:

    $this->app->bind('google.protobuf.audit-log', function ($app) {
        return new AuditLog\LogEntry();
    });
    
  4. Custom Protobuf Extensions Extend generated protobuf classes to add Laravel-specific fields:

    class ExtendedLogEntry extends AuditLog\LogEntry {
        private $laravelUserId;
    
        public function setLaravelUserId(string $id): void {
            $this->laravelUserId = $id;
        }
    
        public function getLaravelUserId(): string {
            return $this->laravelUserId;
        }
    }
    

Workflows

  1. Audit Log Processing

    • Use AuditLog\LogEntry to parse and generate audit logs for compliance.
    • Example: Validate log entries against Google’s schema before storage:
      $validator = new \Google\Protobuf\Internal\Validator();
      $validator->validate($logEntry);
      
  2. Error Handling with Status

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

    • Attach HTTP context to logs using Google\Logging\Type\HttpRequest:
      $httpRequest = new \Google\Logging\Type\HttpRequest();
      $httpRequest->setRequestUrl('https://example.com/api');
      $httpRequest->setRequestMethod('GET');
      $logEntry->setHttpRequest($httpRequest);
      

Integration Tips

  • Laravel Logging Channel Create a custom logging channel to serialize protobuf messages:

    $app['log']->extend('google_protobuf', function () {
        return new GoogleProtobufHandler();
    });
    
  • gRPC Client Integration Use grpc/grpc with protobuf-generated clients:

    $client = new MyServiceClient(
        new \Grpc\Channel('localhost:50051'),
        [
            'protobuf' => new \Google\Protobuf\Internal\Message()
        ]
    );
    
  • Protobuf Schema Validation Validate incoming protobuf payloads:

    use Google\Protobuf\Internal\Validator;
    
    $validator = new Validator();
    if (!$validator->validate($protobufPayload)) {
        throw new \InvalidArgumentException('Invalid protobuf payload');
    }
    

Gotchas and Tips

Pitfalls

  1. Extension Dependency

    • Requires the google/protobuf PHP extension. Ensure your server has it installed:
      pecl install google/protobuf
      
    • Workaround: Use Docker with a preconfigured PHP image (e.g., google/cloud-sdk).
  2. Immutable DTOs

    • Protobuf-generated classes are immutable by design. Use setters to modify fields:
      // ❌ Won't work
      $logEntry->timestamp = new Timestamp();
      
      // ✅ Correct
      $logEntry->setTimestamp(new Timestamp());
      
  3. Schema Evolution

    • Google’s protobuf schemas evolve. Always check for breaking changes in release notes.
    • Tip: Use ^1.0 in composer.json to auto-update to non-breaking changes.
  4. Binary vs. JSON Serialization

    • Protobuf messages serialize to binary by default. Use serializeToJson() for interoperability:
      $json = $logEntry->serializeToJson();
      
  5. Namespace Conflicts

    • Avoid naming collisions with Laravel’s namespaces (e.g., Google\Cloud vs. App\Google).

Debugging

  • Validate Protobuf Messages Use the Validator class to debug malformed messages:

    $validator = new \Google\Protobuf\Internal\Validator();
    $errors = $validator->validate($message);
    dd($errors); // Debug validation issues
    
  • Inspect Generated Classes Dump the structure of a protobuf message:

    dd(get_class_methods($logEntry));
    
  • Check for Deprecated Fields Some fields (e.g., ReservationResourceUsage) are deprecated. Use @deprecated annotations:

    if (method_exists($message, 'getDeprecatedField')) {
        throw new \RuntimeException('Deprecated field used');
    }
    

Tips

  1. Use SDKs First Prefer Google Cloud SDKs (e.g., google/cloud-logging) over direct protobuf usage unless you need custom logic.

  2. Leverage Laravel’s Macroable Extend protobuf classes with Laravel macros:

    \Google\Cloud\CommonProtos\AuditLog\LogEntry::macro('toLaravelArray', function () {
        return [
            'timestamp' => $this->getTimestamp()->getSeconds(),
            'proto_payload' => $this->getProtoPayload()
        ];
    });
    
  3. Protobuf in Migrations Store protobuf payloads in Laravel migrations as JSON:

    Schema::create('audit_logs', function (Blueprint $table) {
        $table->id();
        $table->json('protobuf_payload'); // Store serialized protobuf
        $table->timestamps();
    });
    
  4. Performance Optimization Reuse protobuf message instances to avoid serialization overhead:

    $logEntry = new AuditLog\LogEntry();
    // Reuse $logEntry across requests
    
  5. Testing Protobuf Logic Use Laravel’s Mockery to test protobuf interactions:

    $mockLogEntry = Mockery::mock(AuditLog\LogEntry::class);
    $mockLogEntry->shouldReceive('getTimestamp')->andReturn(new Timestamp());
    
  6. CI/CD Considerations Ensure your CI pipeline installs the google/protobuf extension:

    # Example GitHub Actions
    services:
      php:
        image: php:8.2-cli
        options: --entrypoint /bin/sh
    before_script:
      - pecl install google/protobuf
    
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.
althinect/enum-permission
andydefer/laravel-actions
aimeos/prisma
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
christhompsontldr/laravel-inky
spatie/mailcoach-vapor