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 installs the generated Protocol Buffer (protobuf) classes for Google API common types.

  2. First Use Case: Use the package to define request/response payloads for Google Cloud APIs. For example, to work with quota limits:

    use Google\Api\QuotaSettings;
    use Google\Api\QuotaLimit;
    
    $quotaLimit = new QuotaLimit();
    $quotaLimit->setMaxRequestsPerMinute(1000);
    
    $quotaSettings = new QuotaSettings();
    $quotaSettings->setLimit($quotaLimit);
    
  3. Key Classes to Explore:

    • google/api/Service.proto (API service definitions)
    • google/api/FieldBehavior.proto (Field behavior metadata)
    • google/api/MethodSettings.proto (Method-level configurations)
    • google/api/ResourceDescriptor.proto (Resource definitions)
  4. Documentation:


Implementation Patterns

Core Workflows

1. API Request/Response Modeling

Use the generated classes to structure API payloads. Example for a custom API:

use Google\Api\MethodSettings;
use Google\Api\ResourceDescriptor;

$methodSettings = new MethodSettings();
$methodSettings->setIdempotencyLevel(MethodSettings::IDEMPOTENCY_LEVEL_UNSPECIFIED);

$resourceDescriptor = new ResourceDescriptor();
$resourceDescriptor->setName('projects');

2. Field Behavior and Validation

Leverage FieldBehavior and FieldInfo for metadata-driven validation:

use Google\Api\FieldBehavior;
use Google\Api\FieldInfo;

$fieldInfo = new FieldInfo();
$fieldInfo->setBehavior(FieldBehavior::OPTIONAL);
$fieldInfo->setJsonName('custom_field');

3. Quota and Rate Limiting

Define quota limits for API methods:

use Google\Api\QuotaSettings;
use Google\Api\QuotaLimit;

$quotaLimit = new QuotaLimit();
$quotaLimit->setMaxRequestsPerMinute(1000);
$quotaLimit->setMaxRequestsPer100Seconds(10000);

$quotaSettings = new QuotaSettings();
$quotaSettings->setLimit($quotaLimit);

4. Resource Descriptors

Define resources and their permissions:

use Google\Api\ResourceDescriptor;
use Google\Api\ResourcePermission;

$resourcePermission = new ResourcePermission();
$resourcePermission->setName('projects.update');
$resourcePermission->setTitle('Update Project');

$resourceDescriptor = new ResourceDescriptor();
$resourceDescriptor->setName('projects');
$resourceDescriptor->setPermissions([$resourcePermission]);

5. Integration with Google Cloud Clients

Use these classes alongside Google Cloud PHP SDKs (e.g., google/cloud-logging):

use Google\Cloud\Logging\V2\LogEntry;
use Google\Api\LogBucket;

$logBucket = new LogBucket();
$logBucket->setAnalyticsEnabled(true);

Laravel-Specific Patterns

1. Request Validation with Form Requests

Extend Laravel's FormRequest to validate against protobuf schemas:

use Illuminate\Foundation\Http\FormRequest;
use Google\Api\QuotaSettings;

class StoreQuotaRequest extends FormRequest
{
    public function rules()
    {
        return [
            'max_requests_per_minute' => 'required|integer',
            'max_requests_per_100_seconds' => 'required|integer',
        ];
    }

    public function validated()
    {
        $data = parent::validated();
        $quotaSettings = new QuotaSettings();
        $quotaSettings->setLimit(new QuotaLimit([
            'max_requests_per_minute' => $data['max_requests_per_minute'],
            'max_requests_per_100_seconds' => $data['max_requests_per_100_seconds'],
        ]));
        return $quotaSettings;
    }
}

2. API Response Transformation

Convert protobuf responses to Laravel-friendly formats:

use Illuminate\Http\JsonResponse;
use Google\Api\MethodSettings;

public function show(MethodSettings $methodSettings)
{
    return new JsonResponse([
        'idempotency_level' => $methodSettings->getIdempotencyLevel(),
        'name' => $methodSettings->getName(),
    ]);
}

3. Service Container Binding

Bind protobuf classes to Laravel's service container for dependency injection:

$app->bind(
    Google\Api\Service::class,
    function ($app) {
        return new Google\Api\Service();
    }
);

4. Event Handling with Protobuf Payloads

Dispatch events with protobuf payloads:

use Illuminate\Support\Facades\Event;

Event::dispatch(new QuotaUpdated(
    $quotaSettings
));

5. Artisan Commands for Protobuf Operations

Create custom Artisan commands to interact with protobuf schemas:

use Illuminate\Console\Command;
use Google\Api\ResourceDescriptor;

class GenerateResourceDescriptorCommand extends Command
{
    protected $signature = 'protobuf:generate-resource {name}';
    protected $description = 'Generate a ResourceDescriptor for a given name';

    public function handle()
    {
        $resource = new ResourceDescriptor();
        $resource->setName($this->argument('name'));
        // Save or log the resource
    }
}

Gotchas and Tips

Pitfalls

  1. Protobuf Version Compatibility:

    • The package requires Protobuf v4+. Ensure your google/protobuf dependency is updated:
      composer require google/protobuf:^4.0
      
    • Gotcha: Older versions (e.g., v3) may cause runtime errors. Check the changelog for compatibility notes.
  2. Naming Conventions:

    • Protobuf-generated classes use PascalCase (e.g., QuotaLimit), while JSON fields may use snake_case or camelCase.
    • Tip: Use getJsonName() or setJsonName() to align with API expectations:
      $fieldInfo->setJsonName('snake_case_field');
      
  3. Immutable Fields:

    • Some protobuf fields are read-only after initialization. Use setters before serialization:
      $methodSettings->setIdempotencyLevel(MethodSettings::IDEMPOTENCY_LEVEL_REQUIRED);
      // ❌ Avoid modifying after serialization!
      
  4. Circular References:

    • Protobuf messages may contain self-referential fields (e.g., nested resources). Ensure proper hydration/dehydration:
      $resource->setParent($parentResource); // Valid
      $parentResource->setChild($resource); // May cause infinite loops!
      
  5. Deprecated Fields:

    • Some fields (e.g., Endpoint.aliases) were un-deprecated in later versions. Check the changelog for updates.

Debugging Tips

  1. Serialization Errors:

    • Use json_encode() with JSON_PRETTY_PRINT to debug malformed protobuf payloads:
      $json = json_encode($protobufObject, JSON_PRETTY_PRINT);
      dd($json); // Inspect for missing/incorrect fields
      
  2. Field Validation:

    • Validate fields before serialization:
      if (!$quotaLimit->getMaxRequestsPerMinute()) {
          throw new \InvalidArgumentException('Max requests per minute is required.');
      }
      
  3. Logging Protobuf Objects:

    • Log protobuf objects as JSON for debugging:
      \Log::debug('Protobuf payload', [
          'data' => json_decode(json_encode($protobufObject), true),
      ]);
      
  4. Protobuf Schema Inspection:

    • Use the Protobuf Inspector to explore generated classes:
      $reflection = new \ReflectionClass(QuotaLimit::class);
      foreach ($reflection->getProperties() as $property) {
          \Log::debug($property->getName());
      }
      

Extension Points

  1. Custom Protobuf Extensions:
    • Extend protobuf messages with custom fields using oneof or extensions:
      $methodSettings->
      
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