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

Common Protos Laravel Package

google/common-protos

Generated PHP classes for Google’s common Protocol Buffer types used across the Google API ecosystem. Distributed as the google/common-protos Composer package under Apache 2.0 and designed to be stable for use in your applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require google/common-protos
    

    This provides protocol buffer classes for Google API common types (e.g., google.api.Http, google.protobuf.Timestamp).

  2. First Use Case: Validate API request/response structures against Google’s standardized proto definitions. Example: Define a request payload using google.api.HttpRule:

    use Google\Api\HttpRule;
    use Google\Protobuf\Timestamp;
    
    $httpRule = new HttpRule();
    $httpRule->setSelector('com.example.MyService.CreateRequest');
    $httpRule->setGet('/v1/{name=projects/*}');
    
  3. Key Classes to Explore:

    • google.api.Http (for REST/HTTP mappings)
    • google.protobuf.Timestamp (for time handling)
    • google.api.MethodSettings (for API method configurations)
    • google.api.FieldBehavior (for field metadata)

Where to Look First

  • API Reference: Google Cloud PHP Docs
  • Generated Classes: Browse vendor/google/common-protos/src/ for auto-generated proto classes.
  • Changelog: Review recent updates (e.g., FieldInfo, QuotaFailure) for breaking changes.

Implementation Patterns

1. API Request/Response Validation

Pattern: Use proto classes to enforce schema compliance in Laravel requests/responses.

use Google\Api\HttpRule;
use Illuminate\Http\Request;

public function validateRequest(Request $request) {
    $httpRule = new HttpRule();
    $httpRule->setPost('/v1/messages');
    $httpRule->setBody('type.googleapis.com/google.example.v1.Message');

    // Validate against $httpRule->getBody() in middleware
}

2. Time Handling with Timestamp

Pattern: Convert Carbon/Laravel timestamps to protobuf-compatible formats.

use Google\Protobuf\Timestamp;

public function toProtoTimestamp(\Carbon\Carbon $carbon) {
    $timestamp = new Timestamp();
    $timestamp->setSeconds($carbon->getTimestamp());
    $timestamp->setNanos($carbon->getMicroseconds() * 1000);
    return $timestamp;
}

3. Method-Level Configurations

Pattern: Attach MethodSettings to API routes for metadata (e.g., quota, auth).

use Google\Api\MethodSettings;

Route::post('/messages', function () {
    $settings = new MethodSettings();
    $settings->setName('com.example.CreateMessage');
    $settings->setHttpRule(new HttpRule(['get' => '/v1/messages']));
    // Use $settings in middleware or service layer
});

4. Extension Points

Pattern: Extend proto messages with custom fields using oneof or extensions.

use Google\Api\FieldBehavior;

$fieldInfo = new \Google\Api\FieldInfo();
$fieldInfo->setBehavior(FieldBehavior::IDENTIFIER);
$fieldInfo->setJsonName('custom_field');

5. Integration with Google Cloud Clients

Pattern: Pair with google/cloud-* SDKs for seamless protobuf serialization.

use Google\Cloud\Logging\V2\LoggingServiceClient;

$client = new LoggingServiceClient();
$entry = new \Google\Logging\Type\LogEntry();
$entry->setTimestamp($this->toProtoTimestamp(now()));
$client->writeLogEntries(...);

Workflow Tips

  • Laravel Service Layer: Centralize protobuf conversions in a ProtobufService.
  • Middleware: Validate incoming requests against proto schemas (e.g., HttpRule).
  • Testing: Use Google\Protobuf\Internal\Message assertions in PHPUnit.

Gotchas and Tips

Pitfalls

  1. Protobuf Version Mismatch:

    • Issue: Classes may break if google/protobuf dependency version diverges.
    • Fix: Pin google/protobuf:^5.0 in composer.json (see v4.8.3).
  2. Deprecated Fields:

    • Issue: Fields like Endpoint.aliases were un-deprecated in v4.7.0. Check changelogs for resurrected fields.
  3. Naming Collisions:

    • Issue: Protobuf classes (e.g., Timestamp) may conflict with Laravel helpers.
    • Fix: Use fully qualified namespaces (e.g., \Google\Protobuf\Timestamp).
  4. Immutable Fields:

    • Issue: Protobuf fields are immutable. Use clear() or mergeFrom() to modify.
    • Example:
      $timestamp->clear(); // Reset all fields
      $timestamp->mergeFrom($newTimestamp); // Merge another message
      

Debugging Tips

  • Schema Validation: Use google/protobuf:validate to check protobuf messages.
    $message->validate(); // Throws \Google\Protobuf\InvalidArgumentException
    
  • Logging: Enable protobuf debug logs:
    putenv('GRPC_VERBOSITY=DEBUG');
    putenv('GRPC_TRACE=api');
    
  • IDE Support: Use PHPStorm’s "Go to Definition" on protobuf classes to inspect generated code.

Extension Points

  1. Custom Proto Extensions:

    • Define extensions in your .proto files and regenerate:
      extend google.api.FieldInfo {
        string custom_metadata = 1000;
      }
      
    • Regenerate with protoc and include in your project.
  2. Laravel Service Providers:

    • Bind protobuf services in AppServiceProvider:
      $this->app->singleton(\Google\Protobuf\Internal\Message::class, function () {
          return new \Google\Protobuf\Internal\Message();
      });
      
  3. Event Listeners:

    • Listen for protobuf-related events (e.g., validation failures):
      Event::listen(\Google\Protobuf\InvalidArgumentException::class, function ($e) {
          Log::error('Protobuf validation failed: ' . $e->getMessage());
      });
      

Configuration Quirks

  • Autoloader Optimization: The package includes an optimized autoloader (since v3.1.0). Avoid manual PSR-4 overrides.
  • PHP 8.3+: Drop-in support for PHP 8.3 (see v4.6.0). Test with strict_types=1.

Pro Tips

  • Batch Processing: Use google.api.BatchRequest for grouped API calls:
    $batch = new \Google\Api\BatchRequest();
    $batch->addRequests([$request1, $request2]);
    
  • Quota Management: Leverage google.api.QuotaFailure for rate-limiting:
    if ($response->hasQuotaFailure()) {
        $quota = $response->getQuotaFailure();
        Log::warning("Quota exceeded: {$quota->getReason()}");
    }
    
  • Generics Support: Use FieldInfo.referenced_types (added in v4.7.0) for polymorphic fields.
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.
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
anil/file-picker
broqit/fields-ai