flix-tech/avro-php
A PHP library for working with Apache Avro: parse schemas, encode/decode Avro data, and integrate serialization into your apps. Useful for Kafka-style pipelines and data interchange where compact binary formats and schema evolution matter.
Begin by installing the package via Composer:
composer require flix-tech/avro-php
The core entry points are the Encoder and Decoder classes. For a minimal use case—e.g., producing Avro-encoded messages to Kafka—start by defining a schema (as a JSON string or parsed Schema object), then encode PHP arrays/objects:
use Flix\Avro\Encoder;
use Flix\Avro\Schema;
$schemaJson = '{"type":"record","name":"User","fields":[{"name":"id","type":"int"},{"name":"name","type":"string"}]}';
$schema = Schema::parse($schemaJson);
$encoder = new Encoder($schema);
$payload = $encoder->encode(['id' => 123, 'name' => 'Alice']);
// $payload is a binary string suitable for Kafka or storage
The repository’s examples/ folder (if present) or unit tests are the best first reference for practical usage.
.json files or database registries, then load at runtime using Schema::parse(file_get_contents('user.avsc')). This enables version control and reuse across services.User value object that handles its own serialization:
class User {
public function toAvro(): string { /* uses Encoder */ }
public static function fromAvro(string $data): self { /* uses Decoder */ }
}
php-kafka/kafka-php or enqueue/kafka-client by serializing messages to binary Avro before publishing, and deserializing upon consume.Decoder::withSchema() with both writer and reader schemas to handle forward/backward compatibility:
$decoder = new Decoder($newSchema);
$data = $decoder->decode($binaryPayload, $oldSchema); // backward compat
['id' => 123] or ['id' => null]) automatically resolve based on schema unions like ["int", "null"].null values in PHP only encode/decode when explicitly permitted in the schema (e.g., "type": ["null", "string"]). Double-check schema defaults and union ordering.Encoder/Decoder are stateful and should be reused per schema (not instantiated per call). Caching parsed schemas (e.g., via Symfony Cache or Redis) avoids repeated Schema::parse() overhead.["int", "string"]), Avro resolves types by order, not value. PHP values that satisfy multiple types (e.g., 0 as int/string) will encode using the first matching type—ensure your schema order aligns with intended behavior.Schema\ResolverInterface to integrate with Confluent Schema Registry or custom endpoints for dynamic schema loading in microservices.How can I help you explore Laravel packages today?