quarks-tech/protoevent-php
Composer 安装命令:
composer require quarks-tech/protoevent-php
包简介
PHP implementation for ProtoEvent with CloudEvents and AMQP support
README 文档
README
PHP implementation for ProtoEvent with CloudEvents 1.0 and AMQP support.
Features
- CloudEvents 1.0 compliant - Full support for CloudEvents metadata
- Binary and Structured content modes - Flexible message marshaling
- Parking lot pattern - Automatic retries with exponential backoff
- Graceful shutdown - Handles SIGTERM/SIGINT signals
- Symfony integration - Optional bundle for auto-wiring and console commands
- Code generation - protoc plugin generates type-safe publishers and handlers
- In-memory transport - For testing without RabbitMQ
- Interceptors - Middleware support for publishers and subscribers
Requirements
- PHP 8.0+
- ext-amqp (php-amqp extension)
- RabbitMQ 3.x
Installation
composer require quarks-tech/protoevent-php
For Symfony, also install the required dependencies:
composer require symfony/config symfony/dependency-injection symfony/console symfony/http-kernel
Quick Start
Publishing Events
use QuarksTech\ProtoEvent\EventBus\Publisher; use QuarksTech\ProtoEvent\Transport\Amqp\AmqpConnection; use QuarksTech\ProtoEvent\Transport\Amqp\AmqpSender; $connection = new AmqpConnection('localhost', 5672, 'guest', 'guest'); $sender = new AmqpSender($connection); $publisher = new Publisher($sender); // Setup exchange (once per service) $sender->setup($serviceDesc); // Publish using generated typed publisher $typedPublisher = new \Your\Namespace\EventBus\Publisher($publisher); $typedPublisher->publishYourEvent($event);
Consuming Events
use QuarksTech\ProtoEvent\EventBus\Subscriber; use QuarksTech\ProtoEvent\Transport\Amqp\AmqpConnection; use QuarksTech\ProtoEvent\Transport\Amqp\ParkingLotReceiver; use QuarksTech\ProtoEvent\Transport\Amqp\ParkingLotReceiverOptions; $connection = new AmqpConnection('localhost', 5672, 'guest', 'guest'); $receiver = new ParkingLotReceiver($connection, new ParkingLotReceiverOptions( queueName: 'my-consumer', maxRetries: 3, retryBackoffMs: 15000, )); $subscriber = new Subscriber('my-consumer'); // Register handlers using generated registration functions \Your\Namespace\EventBus\Registration::registerYourEventHandler($subscriber, $handler); // Start consuming (blocks until signal) $subscriber->subscribe($receiver);
Code Generation
Install the protoc plugin:
go install github.com/quarks-tech/ddkitapis-generator-go/cmd/protoc-gen-php-eventbus@latest
Generate code:
protoc --php_out=./gen --php-eventbus_out=./gen your_events.proto
Generated Files
For each proto file with event messages (marked with (quarks_tech.protoevent.v1.enabled) = true):
EventBus/ServiceDesc.php- Service descriptorEventBus/EventPublisher.php- Typed publisher interfaceEventBus/Publisher.php- Publisher implementationEventBus/Registration.php- Handler registration functionsEventBus/Handler/*EventHandler.php- Handler interfaces
Symfony Integration
Bundle Registration
// config/bundles.php return [ // ... QuarksTech\ProtoEvent\SymfonyBundle\QuarksTechProtoEventBundle::class => ['all' => true], ];
Configuration
# config/packages/quarks_tech_proto_event.yaml quarks_tech_proto_event: connection: dsn: '%env(RABBITMQ_DSN)%' queues: monolith.v2.subscriptions: parking_lot: true max_retries: 3 monolith.v2.notifications: parking_lot: false prefetch_count: 10
Event Handlers
One handler class per event. Just implement the generated interface:
class SubscriptionCreatedHandler implements SubscriptionCreatedEventHandler { public function handleSubscriptionCreatedEvent(EventContext $ctx, SubscriptionCreatedEvent $event): void { // Handle subscription created } } class SubscriptionUpdatedHandler implements SubscriptionUpdatedEventHandler { public function handleSubscriptionUpdatedEvent(EventContext $ctx, SubscriptionUpdatedEvent $event): void { // Handle subscription updated } }
Handlers are auto-discovered. Events are routed based on type.
Console Commands
Run consumers for specific queues (ideal for Kubernetes deployments):
# Consumes SubscriptionCreated and SubscriptionUpdated events php bin/console protoevent:consume monolith.v2.subscriptions # Run in another pod php bin/console protoevent:consume monolith.v2.notifications
All registered handlers are available to all queues. The subscriber automatically routes incoming events to the matching handler.
Testing with InMemoryTransport
Use the in-memory transport for unit and integration tests:
use QuarksTech\ProtoEvent\EventBus\Publisher; use QuarksTech\ProtoEvent\EventBus\Subscriber; use QuarksTech\ProtoEvent\Transport\InMemory\InMemoryTransport; // Create shared transport $transport = new InMemoryTransport(); // Publisher uses transport as sender $publisher = new Publisher($transport); // Subscriber uses transport as receiver $subscriber = new Subscriber('test-consumer'); // Publish events $publisher->publish('example.v1.TestEvent', $event); // Verify messages $this->assertSame(1, $transport->count()); $messages = $transport->getMessages(); // Consume events $subscriber->subscribe($transport); // Clear for next test $transport->clear(); // clears messages only $transport->reset(); // clears messages and services
Interceptors
Add cross-cutting concerns with interceptors:
use QuarksTech\ProtoEvent\EventBus\PublisherInterceptor; use QuarksTech\ProtoEvent\EventBus\SubscriberInterceptor; // Publisher interceptor class TracingPublisherInterceptor implements PublisherInterceptor { public function intercept(Metadata $metadata, Message $event, callable $next): void { $metadata = $metadata->withExtension('traceid', $this->traceId); $next($metadata, $event); } } // Subscriber interceptor class LoggingSubscriberInterceptor implements SubscriberInterceptor { public function intercept(EventContext $context, mixed $event, callable $next): void { $this->logger->info('Processing: ' . $context->getMetadata()->getType()); $next($context, $event); } } // Add to publisher/subscriber $publisher->withInterceptor(new TracingPublisherInterceptor($tracer)); $subscriber->withInterceptor(new LoggingSubscriberInterceptor($logger));
Architecture
Parking Lot Pattern
Failed messages flow through a retry cycle:
Main Queue → DLX → Wait Queue (TTL) → DLX → Main Queue (retry)
↓
(max retries) → Parking Lot Queue
Queue naming:
{queue}- main processing queue{queue}.wait- wait queue with TTL backoff{queue}.pl- parking lot for permanently failed messages{queue}.dlx- dead letter exchange
Message Marshaling
Binary mode (default): CloudEvents attributes in AMQP headers, payload in body.
Structured mode: Full CloudEvents JSON document in message body (use content type application/cloudevents+json).
Notes:
- Setting
application/cloudevents+jsonimplies JSON payload encoding (protobuf JSON for protobuf messages), matching the Go implementation. - Timestamps are emitted as RFC3339 without fractional seconds for cross-language compatibility.
License
MIT
quarks-tech/protoevent-php 适用场景与选型建议
quarks-tech/protoevent-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.52k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 12 月 26 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「symfony」 「events」 「rabbitmq」 「AMQP」 「event-bus」 「protobuf」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 quarks-tech/protoevent-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 quarks-tech/protoevent-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 quarks-tech/protoevent-php 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Work with RabbitMQ in Laravel.
Microservice RPC through message queues.
PHP AMQP Binding Library
The bundle for easy using json-rpc api on your project
Библиотека для реализаций паттерна Pub/Sub
Wireless Cross-Component Communication
统计信息
- 总下载量: 4.52k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 9
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2022-12-26