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 require google/cloud-common-protos
    
  2. Verify Installation Check autoloaded classes:

    composer dump-autoload
    

    Verify the Google\Cloud\Common\Protos namespace is available.

  3. First Use Case: Audit Logs Use the AuditLog protobuf type to structure log entries:

    use Google\Cloud\Common\Protos\AuditLog;
    
    $log = new AuditLog();
    $log->setAuthenticationInfo(...);
    $log->setServiceName('my-service');
    
  4. Key Classes to Explore

    • Google\Cloud\Common\Protos\AuditLog (Audit logging)
    • Google\Cloud\Common\Protos\Status (Error handling)
    • Google\Cloud\Common\Protos\HttpRequest (HTTP metadata)

Implementation Patterns

Usage Patterns

1. Protobuf Data Transfer Objects (DTOs)

Use generated classes as immutable DTOs for Google Cloud integrations:

use Google\Cloud\Common\Protos\Status;

$status = new Status();
$status->setCode(Status::CODE_INVALID_ARGUMENT);
$status->setMessage('Invalid request payload');

2. Integration with Google Cloud SDKs

Pair with official SDKs (e.g., google/cloud-logging) for seamless protobuf handling:

use Google\Cloud\Logging\V2\LoggingClient;
use Google\Cloud\Common\Protos\AuditLog;

$logging = new LoggingClient();
$logEntry = $logging->entry('my-log', [
    'protoPayload' => AuditLog::class,
    'data' => $auditLog->serializeToJsonString()
]);

3. Custom Protobuf Extensions

Extend protobuf types for domain-specific needs (e.g., adding Laravel metadata):

use Google\Cloud\Common\Protos\HttpRequest;

$request = new HttpRequest();
$request->setRequestUrl('/api/endpoint');
$request->setUserAgent('Laravel/' . app()->version());

4. Validation and Serialization

Validate protobuf payloads before API calls:

use Google\Cloud\Common\Protos\Status;

$status = new Status();
if ($status->getCode() !== Status::CODE_OK) {
    throw new \RuntimeException($status->getMessage());
}

5. Laravel Service Providers

Bind protobuf factories for dependency injection:

// app/Providers/GoogleCloudServiceProvider.php
public function register()
{
    $this->app->bind(AuditLog::class, function () {
        return new AuditLog();
    });
}

Workflows

Audit Logging Workflow

  1. Capture Events Use AuditLog to log sensitive actions (e.g., user updates):

    $auditLog = new AuditLog();
    $auditLog->setServiceName('laravel-auth');
    $auditLog->setMethodName('updateUser');
    
  2. Serialize for Storage Convert to JSON for Google Cloud Logging:

    $serialized = $auditLog->serializeToJsonString();
    
  3. Send to GCP Integrate with google/cloud-logging:

    $logging->writeLogEntry($serialized);
    

Error Handling Workflow

  1. Standardize Errors Use Status for consistent error responses:

    $status = new Status();
    $status->setCode(Status::CODE_PERMISSION_DENIED);
    
  2. Map to Laravel Exceptions Convert protobuf errors to Laravel exceptions:

    throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException(
        $status->getMessage()
    );
    

gRPC Integration Workflow

  1. Define Protobuf Services Extend protobuf definitions for custom gRPC endpoints:

    service MyService {
        rpc LogEvent (AuditLog) returns (Status);
    }
    
  2. Generate PHP Clients Use protoc to generate gRPC clients:

    protoc --php_out=. --grpc_out=. my_service.proto
    
  3. Integrate with Laravel Bind gRPC clients in Laravel’s DI container:

    $this->app->singleton(MyServiceClient::class, function () {
        return new MyServiceClient(...);
    });
    

Integration Tips

1. Protobuf Serialization in Laravel

Use serializeToJsonString() for API payloads:

$response = [
    'status' => $status->serializeToJsonString(),
    'data' => $data
];

2. Laravel Validation Rules

Validate protobuf fields with Laravel’s validator:

$validator = Validator::make($request->all(), [
    'protoPayload' => 'required|string',
]);

3. Caching Protobuf Instances

Cache frequently used protobuf objects (e.g., Status for errors):

$statusCache = Cache::remember('error_status', 3600, function () {
    return new Status();
});

4. Testing Protobuf Logic

Use PHPUnit to test protobuf serialization:

public function testAuditLogSerialization()
{
    $auditLog = new AuditLog();
    $serialized = $auditLog->serializeToJsonString();
    $this->assertJson($serialized);
}

5. Protobuf in Laravel Queues

Serialize protobuf objects for queue jobs:

Queue::push(function () use ($auditLog) {
    $serialized = $auditLog->serializeToJsonString();
    // Process $serialized
});

Gotchas and Tips

Pitfalls

1. PHP Extensions Required

  • Issue: The package depends on google/protobuf, which requires PHP extensions (protobuf).
  • Fix: Ensure your php.ini includes:
    extension=protobuf.so
    
  • Debugging: Check for missing extensions with:
    php -m | grep protobuf
    

2. Immutable Protobuf Objects

  • Issue: Protobuf objects are immutable; modifying fields requires creating new instances.
  • Fix: Use mergeFrom() or setter methods:
    $newLog = clone $auditLog;
    $newLog->setMethodName('new_method');
    

3. Version Conflicts

  • Issue: Conflicts with google/protobuf versions (e.g., ^3.0 vs ^4.0).
  • Fix: Pin versions in composer.json:
    "google/protobuf": "^3.20.0"
    

4. Serialization Quirks

  • Issue: serializeToJsonString() may omit default values.
  • Fix: Explicitly set fields before serialization:
    $status->setCode(Status::CODE_OK);
    $status->setMessage('OK');
    

5. Deprecated Fields

  • Issue: Some fields (e.g., ReservationResourceUsage) are deprecated.
  • Fix: Use isDeprecated() checks or avoid deprecated fields:
    if ($log->hasDeprecatedFields()) {
        Log::warning('Deprecated protobuf fields detected');
    }
    

6. gRPC Performance Overhead

  • Issue: Protobuf/gRPC adds latency for simple requests.
  • Fix: Use REST APIs for lightweight interactions; reserve gRPC for high-throughput services.

Debugging

1. Protobuf Validation Errors

  • Symptom: InvalidProtocolBufferException during deserialization.
  • Debug:
    try {
        $status = Status::deserialize($json);
    } catch (\InvalidArgumentException $e) {
        Log::error('Protobuf deserialization failed: ' . $e->getMessage());
    }
    

2. Missing Fields in Serialization

  • Symptom: Serialized JSON lacks expected fields.
  • Debug: Check for unset fields:
    $this->assertNotNull($status->getCode(), 'Status code must be set');
    

3. Extension Loading Failures

  • Symptom: Class 'Google\Protobuf\Internal\Message' not found.
  • Debug: Verify protobuf extension is enabled:
    php -i | grep 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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport