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 Google APIs. Stable, backwards-compatible shared dependencies published as the google/common-protos Composer package (Apache 2.0), part of the Google Cloud PHP ecosystem.

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: Validate API request/response structures against Google's standardized protobuf definitions. Example:

    use Google\Api\FieldBehavior;
    use Google\Api\ResourcePermission;
    
    // Define a resource permission for an API method
    $permission = new ResourcePermission();
    $permission->setName('projects.update');
    $permission->setTitle('Update Project');
    
    // Use FieldBehavior enum
    $behavior = FieldBehavior::IDENTIFIER;
    
  3. Key Classes to Explore:

    • Google\Api\MethodSettings (for API method configurations)
    • Google\Api\ResourcePermission (for IAM-like permissions)
    • Google\Api\FieldBehavior (field metadata)
    • Google\Api\QuotaFailure (for quota-related errors)
  4. Documentation:


Implementation Patterns

1. API Contract Validation

Use protobuf classes to enforce request/response schemas in Laravel services:

// In a Laravel service class
public function validateRequest(array $data): void
{
    $requestProto = new Google\Api\MethodSettings();
    $requestProto->setName($data['method_name']);

    // Validate against protobuf structure
    if (!isset($data['resource_permissions'])) {
        throw new \InvalidArgumentException('Missing resource permissions');
    }
}

2. Dynamic API Generation

Leverage protobuf types to generate API clients dynamically:

// Example: Build a client for a hypothetical API
$client = new Google\Cloud\ServiceClient([
    'apiMethodSettings' => [
        new Google\Api\MethodSettings([
            'name' => 'v1.projects.update',
            'resourcePermissions' => [
                new Google\Api\ResourcePermission([
                    'name' => 'projects.update',
                    'title' => 'Update Project',
                ]),
            ],
        ]),
    ],
]);

3. Error Handling

Standardize error responses using protobuf-defined error types:

// In an Exception Handler
public function render($request, Throwable $exception)
{
    if ($exception instanceof \Google\ApiCore\ApiException) {
        $errorProto = $exception->getProto();
        return response()->json([
            'error' => [
                'code' => $errorProto->getCode(),
                'message' => $errorProto->getMessage(),
                'details' => $errorProto->getDetails(),
            ],
        ]);
    }
    return parent::render($request, $exception);
}

4. Laravel Service Providers

Register protobuf-based services in Laravel:

// In AppServiceProvider
public function register()
{
    $this->app->singleton(Google\Api\FieldBehavior::class, function () {
        return new Google\Api\FieldBehavior();
    });
}

5. Testing

Use protobuf classes in PHPUnit tests to validate API contracts:

public function testApiMethodSettings()
{
    $settings = new Google\Api\MethodSettings();
    $settings->setName('test.method');

    $this->assertEquals('test.method', $settings->getName());
}

6. Integration with Google Cloud Clients

Pair with Google Cloud PHP SDKs (e.g., google/cloud-core) for unified protobuf handling:

use Google\Cloud\Core\Api\ApiInterface;
use Google\Api\MethodSettings;

$api = new class implements ApiInterface {
    public function getMethodSettings(): MethodSettings
    {
        return new MethodSettings([
            'name' => 'custom.method',
            'resourcePermissions' => [...],
        ]);
    }
};

Gotchas and Tips

1. Protobuf Version Compatibility

  • Gotcha: The package requires Protobuf PHP v5+ (since v4.8.3). Ensure your google/protobuf dependency is updated:
    composer require google/protobuf:^5.0
    
  • Tip: If using Laravel Mix or Vite, exclude protobuf files from asset compilation to avoid conflicts:
    // vite.config.js
    export default {
      build: {
        rollupOptions: {
          external: ['**/vendor/google/protobuf/**'],
        },
      },
    };
    

2. Namespace Conflicts

  • Gotcha: Protobuf classes use Google\Api namespace, which may conflict with Laravel's Google facade or other libraries.
  • Tip: Use fully qualified namespaces or aliases:
    use Google\Api\FieldBehavior as ProtoFieldBehavior;
    

3. Serialization/Deserialization

  • Gotcha: Protobuf classes require explicit serialization for JSON/API responses:
    $proto = new Google\Api\MethodSettings();
    $json = $proto->serializeToJsonString(); // Not auto-magic!
    
  • Tip: Create helper methods in a Laravel service:
    class ProtoHelper {
        public static function toJson($proto): string
        {
            return $proto->serializeToJsonString();
        }
    }
    

4. Performance Considerations

  • Gotcha: Protobuf classes are heavy for large-scale serialization. Cache instances where possible:
    $cachedProto = Cache::remember('api.method.settings', 3600, function () {
        return new Google\Api\MethodSettings();
    });
    
  • Tip: Use google/protobuf’s GeneratedMessage optimizations for repeated use:
    $proto = new Google\Api\MethodSettings();
    $proto->clear(); // Reuse instances
    

5. Debugging Protobuf Issues

  • Gotcha: Protobuf validation errors can be cryptic. Enable debug logging:
    \Google\Protobuf\Internal\Debug::setEnabled(true);
    
  • Tip: Use var_dump($proto->debugString()) to inspect raw protobuf data.

6. Extending Protobuf Classes

  • Gotcha: Protobuf classes are immutable by design. Avoid direct property modification.
  • Tip: Use builders or copy methods:
    $newProto = $originalProto->toBuilder()->setName('new.name')->buildPartial();
    

7. Laravel Caching

  • Tip: Cache protobuf instances in Laravel’s cache store:
    $settings = Cache::get('api.settings', function () {
        return new Google\Api\MethodSettings();
    });
    

8. Common Pitfalls

  • Missing Fields: Protobuf requires all required fields to be set before serialization.
    $proto = new Google\Api\MethodSettings();
    // $proto->serializeToJsonString(); // Throws exception if required fields are missing
    
  • Enum Values: Always use Google\Api\FieldBehavior::IDENTIFIER (not strings).
  • Deprecated Fields: Check changelogs (e.g., Endpoint.aliases was un-deprecated in v4.7.0).

9. Testing Protobuf Logic

  • Tip: Use Google\Protobuf\Internal\TestUtil for assertions:
    use Google\Protobuf\Internal\TestUtil;
    
    public function testProtoEquality()
    {
        $proto1 = new Google\Api\MethodSettings();
        $proto2 = new Google\Api\MethodSettings();
        $this->assertTrue(TestUtil::equalTo($proto1, $proto2));
    }
    

10. Laravel Service Container

  • Tip: Bind protobuf factories to Laravel’s container:
    $this->app->bind(Google\Api\MethodSettings::class, function () {
        return new Google\Api\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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata