micromus/kafka-bus-domain 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

micromus/kafka-bus-domain

Composer 安装命令:

composer require micromus/kafka-bus-domain

包简介

Messages Builder for Kafka Bus

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style GitHub PHPStan

A PHP library for structuring, serializing, and deserializing Kafka messages. It provides typed message payloads with automatic casting, domain event messages, and factory helpers for both production and testing.

Installation

composer require micromus/kafka-bus-messages

Core Concepts

  • Payload — a flexible key-value container that supports typed attribute casting (dates, integers, floats, nested payloads, collections).
  • JsonMessage — a Payload that serializes itself directly to a JSON Kafka message.
  • DomainMessage — a structured message that wraps an attributes object with a domain event type (create, update, delete) and a list of dirty (changed) fields.
  • Casters — classes that convert raw values on read (cast) and convert them back for serialization (rollback).

Usage

1. Defining a Domain Message

Extend Payload and define casters in definitionCasters() to type your fields automatically.

use Micromus\KafkaBusMessages\Data\Payload;
use Micromus\KafkaBusMessages\Data\Casters\PayloadCaster;
use Micromus\KafkaBusMessages\Data\Casters\CollectionCaster;
use Micromus\KafkaBusMessages\Data\Casters\IntegerCaster;
 
/**
 * @property int            $id
 * @property string         $name
 * @property CategoryPayload    $category
 * @property AttributePayload[] $attributes
 */
class ProductMessage extends \Micromus\KafkaBusMessages\DomainMessage
{
    public function getKey(): ?string
    {
        return (string) $this->id;
    }
 
    protected function definitionCasters(): array
    {
        return [
            'id'         => new IntegerCaster(),
            'category'   => new PayloadCaster(CategoryPayload::class),
            'attributes' => new CollectionCaster(new PayloadCaster(AttributePayload::class)),
        ];
    }
}
 
// Create from a raw array (e.g. decoded JSON)
$product = ProductMessage::from([
    'id'   => '42',
    'name' => 'Laptop',
    'category' => ['id' => 1, 'name' => 'Electronics'],
    'attributes' => [
        ['id' => 10, 'name' => 'Color', 'value' => 'Silver'],
    ],
]);
 
echo $product->id;               // int(42)
echo $product->category->name;   // string("Electronics")
echo $product->attributes[0]->value; // string("Silver")

2. Available Casters

Caster Description
IntegerCaster Casts value to int
FloatCaster Casts value to float
DateTimeCaster Parses/formats DateTimeInterface with a configurable format
PayloadCaster Hydrates a nested Payload subclass from an array
CollectionCaster Applies another caster to each item in an array
NullableCaster Wraps any caster to allow null values
use Micromus\KafkaBusMessages\Data\Casters\DateTimeCaster;
use Micromus\KafkaBusMessages\Data\Casters\NullableCaster;
use Micromus\KafkaBusMessages\Data\Casters\FloatCaster;
 
protected function definitionCasters(): array
{
    return [
        'published_at' => new DateTimeCaster('Y-m-d\TH:i:s.uP'), // default format
        'deleted_at'   => new NullableCaster(new DateTimeCaster()),
        'price'        => new FloatCaster(),
    ];
}

3. Sending a JSON Message

JsonMessage extends Payload and implements ProducerMessageInterface, so it can be published directly to Kafka.

use Micromus\KafkaBusMessages\JsonMessage;
 
$message = new JsonMessage([
    'order_id' => 123,
    'status'   => 'shipped',
]);
 
// Produces: {"order_id":123,"status":"shipped"}
$message->toPayload();

4. Sending a Domain Message

DomainMessage wraps an attributes object with a domain event type and a list of changed fields.

use Micromus\KafkaBusMessages\DomainMessage;
use Micromus\KafkaBusMessages\DomainEventEnum;
 
$attributes = [
    'id'   => 42,
    'name' => 'Laptop Pro',
    'category'   => ['id' => 1, 'name' => 'Electronics'],
    'attributes' => [],
];
 
// create / update / delete
$message = new ProductMessage(
    attributes: $attributes,
    event: DomainEventEnum::Update,
    dirty: ['name'],
);
 
// Produces JSON:
// {
//   "event": "update",
//   "attributes": { "id": 42, "name": "Laptop Pro", ... },
//   "dirty": ["name"]
// }
$message->toPayload();
 
// The Kafka partition key comes from getKey() on the attributes object
$message->getKey(); // "42"


// Send to bus
$bus->publish($message);

5. Consuming a Domain Message

Use DomainMessageFactory to deserialize an incoming Kafka message into a typed DomainMessage.

use Micromus\KafkaBusMessages\Factories\DomainMessageFactory;

class ProductConsumer
{
    #[MessageFactory(new DomainMessageFactory(ProductMessage::class))]
    public function __invoke(ProductMessage $message)
    {
        echo $message->event->value;          // "update"
        echo $message->name;      // "Laptop Pro"
    }
}

6. Testing Helpers

The library ships with factory base classes to generate realistic test data via Faker.

Define a test factory:

use Micromus\KafkaBusMessages\Testing\DomainMessageTestFactory;
 
/**
 * @extends DomainMessageTestFactory<ProductPayload>
 */
final class ProductTestFactory extends DomainMessageTestFactory
{
    protected string $messageClass = ProductMessage::class;
 
    public function definition(): array
    {
        return [
            'id'         => $this->faker->numberBetween(1, 9999),
            'name'       => $this->faker->sentence(),
            'category'   => CategoryPayloadTestFactory::new()->makeArray(),
            'attributes' => [
                AttributePayloadTestFactory::new()->makeArray(),
            ],
        ];
    }
}

Use it in tests:

// Build a typed DomainMessage with default fake data
$message = ProductMessageTestFactory::new()->message();
 
// Override specific fields
$message = ProductMessageTestFactory::new()
    ->withEvent(DomainEventEnum::Delete)
    ->withDirty(['name', 'category'])
    ->message(['name' => 'Laptop Pro']);
 
// Build a raw RdKafka\Message for lower-level consumer tests
$rdKafkaMessage = ProductMessageTestFactory::new()->make();
 
// Build just the raw array
$array = ProductTestFactory::new()->makeArray();

For payload-only factories, extend PayloadTestFactory:

use Micromus\KafkaBusMessages\Testing\PayloadTestFactory;
 
/**
 * @extends PayloadTestFactory<CategoryPayload>
 */
final class CategoryPayloadTestFactory extends PayloadTestFactory
{
    protected string $payloadClass = CategoryPayload::class;
 
    public function definition(): array
    {
        return [
            'id'   => $this->faker->numberBetween(1, 9999),
            'name' => $this->faker->word(),
        ];
    }
}
 
$category = CategoryPayloadTestFactory::new()->payload();

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

micromus/kafka-bus-domain 适用场景与选型建议

micromus/kafka-bus-domain 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 10 月 16 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「message」 「dto」 「kafka」 「apache kafka」 「micromus」 「kafka-bus」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 micromus/kafka-bus-domain 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 micromus/kafka-bus-domain 我们能提供哪些服务?
定制开发 / 二次开发

基于 micromus/kafka-bus-domain 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 3
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 18
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-10-16