kariricode / serializer
Multi-format serialization engine for PHP 8.4+ — JSON, XML, CSV, QueryString, #[Serialize] attributes, powered by kariricode/property-inspector. ARFA 1.3.
Fund package maintenance!
Requires
- php: ^8.4
- kariricode/property-inspector: ^2.0
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-27 02:29:31 UTC
README
Multi-format serialization for PHP 8.4+.
JSON · XML · CSV · QueryString · #[Serialize] attributes · zero dependencies.
Installation · Quick Start · Attribute API · All Encoders · CI Integration · Architecture
The Problem
Different API consumers demand different wire formats — REST clients expect JSON, B2B integrations require XML, data pipelines need CSV, and legacy systems use query strings. Writing separate serializers for each format creates unsustainable duplication:
// Repeated across every endpoint, every format $json = json_encode($dto); // no field control, no groups $xml = $this->buildXmlManually($dto); // 40 lines of DOMDocument boilerplate $csv = implode(',', array_values(get_object_vars($dto))); // completely unpredictable
The Solution
use KaririCode\Serializer\Provider\SerializerServiceProvider; use KaririCode\Serializer\Attribute\Serialize; final readonly class ProductDTO { #[Serialize(groups: ['api', 'export'])] public string $name; #[Serialize(groups: ['api'])] public float $price; #[Serialize(groups: ['export'], name: 'SKU')] public string $sku; } $provider = new SerializerServiceProvider(); $serializer = $provider->createAttributeSerializer($provider->createConfiguration()); $dto = new ProductDTO('Laptop Pro', 2999.99, 'LAP-PRO-001'); // Format-agnostic serialization — same DTO, any format $json = $serializer->serialize($dto, 'json', groups: ['api']); $csv = $serializer->serialize($dto, 'csv', groups: ['export']); $xml = $serializer->serialize($dto, 'xml', groups: ['api', 'export']); $qs = $serializer->serialize($dto, 'query_string', groups: ['api']);
Features
- ✅ 4 built-in encoders — JSON, XML, CSV, QueryString — same
serialize()call - ✅ Serialization groups — control which fields appear in which context
- ✅ Field renaming —
#[Serialize(name: 'SKU')]maps to the desired wire name - ✅ Attribute-driven API —
#[Serialize]with groups, aliases, ordering - ✅ Zero external dependencies — only
kariricode/property-inspectorfor reflection - ✅ PHPStan Level 9 + Psalm Level 1 — full static-analysis compliance
- ✅ 100% test coverage — 100% Classes/Methods/Lines
- ✅ ARFA 1.3 compliant —
final readonlydomain classes
Requirements
| Requirement | Version |
|---|---|
| PHP | 8.4+ |
| Composer | 2.x |
| kariricode/property-inspector | ^2.0 |
Installation
composer require kariricode/serializer
Quick Start
1. Direct Encoder API
use KaririCode\Serializer\Provider\SerializerServiceProvider; $provider = new SerializerServiceProvider(); $serializer = $provider->createSerializer(); // Serialize any array to any format $json = $serializer->encode(['name' => 'Alice', 'age' => 30], 'json'); $xml = $serializer->encode(['name' => 'Alice', 'age' => 30], 'xml'); $csv = $serializer->encode([['name', 'age'], ['Alice', 30]], 'csv'); $qs = $serializer->encode(['name' => 'Alice', 'age' => 30], 'query_string');
2. Attribute API (DTO-driven)
use KaririCode\Serializer\Attribute\Serialize; final readonly class InvoiceDTO { #[Serialize(groups: ['api', 'export'])] public string $id; #[Serialize(groups: ['api'], name: 'totalAmount')] public float $total; #[Serialize(groups: ['export'])] public string $customerName; }
Real-World Use Cases
Use Case 1 — REST API JSON Response with Groups
// Public API — only expose id, name, price $json = $serializer->serialize($productDto, 'json', groups: ['api']); // Internal export — expose all fields including cost_price $csv = $serializer->serialize($productDto, 'csv', groups: ['export']);
Use Case 2 — B2B XML Integration
final readonly class InvoiceDTO { #[Serialize(groups: ['b2b'], name: 'InvoiceNumber')] public string $id; #[Serialize(groups: ['b2b'], name: 'TotalAmount')] public float $total; } $xml = $serializer->serialize($invoiceDto, 'xml', groups: ['b2b']); // <root><InvoiceNumber>INV-001</InvoiceNumber><TotalAmount>1500.00</TotalAmount></root>
Use Case 3 — CSV Data Export Pipeline
// Export 50k rows to CSV for data warehouse foreach ($productBatch as $product) { $csvRow = $serializer->serialize($product, 'csv', groups: ['export']); $stream->write($csvRow); }
Use Case 4 — Legacy Query String API Integration
// Third-party API requires form-encoded query string $queryString = $serializer->serialize($requestDto, 'query_string'); $response = $httpClient->get("https://legacy.api.com/endpoint?{$queryString}");
All 4 Encoders
| Format | Alias | Best For |
|---|---|---|
| JSON | json |
REST APIs, frontend consumption, storage |
| XML | xml |
B2B integrations, SOAP-adjacent, config files |
| CSV | csv |
Data exports, spreadsheets, data pipelines |
| QueryString | query_string |
URL parameters, form submissions, legacy APIs |
Decoder (reverse)
$array = $serializer->decode($jsonString, 'json'); $array = $serializer->decode($xmlString, 'xml'); $array = $serializer->decode($csvString, 'csv'); $array = $serializer->decode($qs, 'query_string');
Attribute-Driven DTO Serialization
The #[Serialize] attribute gives per-field control over wire format representation:
use KaririCode\Serializer\Attribute\Serialize; final readonly class OrderDTO { #[Serialize(groups: ['api', 'admin'], name: 'order_id')] public string $id; #[Serialize(groups: ['api'])] public string $status; #[Serialize(groups: ['admin'], name: 'internal_cost')] public float $costPrice; // Fields without #[Serialize] are excluded from ALL groups public string $secretToken; }
CI Integration
- name: Run quality pipeline run: | kcode init kcode quality
| Tool | Level | Result |
|---|---|---|
php-cs-fixer |
KaririCode standard | ✅ |
phpstan |
Level 9 | ✅ |
psalm |
Level 1 | ✅ |
phpunit + pcov |
100% coverage | ✅ |
Architecture
Design Decisions
| Decision | Rationale | ADR |
|---|---|---|
| Encoder registry keyed by format | Pluggable new formats without engine changes | ADR-001 |
#[Serialize] attribute groups |
Context-sensitive field exposure per consumer | ADR-002 |
| Zero runtime deps for encoders | JSON/XML/CSV via PHP 8.4+ built-ins only | ADR-003 |
PropertyInspector for reflection |
Caching; no per-call new ReflectionClass() |
ADR-004 |
Project Stats
| Metric | Value |
|---|---|
| Encoder types | 4 (JSON, XML, CSV, QueryString) |
| External dependencies | 1 (kariricode/property-inspector) |
| Line coverage | 100% |
| PHPStan level | 9 (0 errors) |
| Psalm level | 1 (0 errors) |
Ecosystem Integration
| Library | Integration |
|---|---|
| kariricode/normalizer | Normalize complex types before serialization |
| kariricode/sanitizer | Sanitize before reverse-serializing (import) |
| kariricode/validator | Validate deserialized payload before processing |
| kariricode/property-inspector | Reflection caching for #[Serialize] scanning |
| kariricode/devkit | kcode quality CI pipeline runner |
Development
This package keeps no QA tools in require-dev. KaririCode Devkit (kcode) installs PHPUnit, PHPStan, Psalm, PHP-CS-Fixer and Rector into .kcode/ (git-ignored) the first time a command needs them.
Install kcode once (PHP 8.4+):
wget https://github.com/KaririCode-PHP/devkit/releases/latest/download/kcode.phar chmod +x kcode.phar sudo mv kcode.phar /usr/local/bin/kcode
From the repository root:
composer install # runtime dependencies only kcode init # generate .kcode/ and install the toolchain (first run) kcode test # PHPUnit (--coverage, --suite=Unit, any PHPUnit option) kcode analyse # PHPStan, then Psalm kcode cs:fix # apply the code style (--check reports only) kcode quality # the CI gate: cs-fixer, PHPStan, Psalm, PHPUnit kcode quality --docker # the same gate inside the kcode PHP container
Project overrides go in devkit.php (kcode init --config writes a template); run kcode init after editing it. kcode clean --all removes .kcode/.
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feat/my-encoder - Run:
kcode quality— all 4 tools must pass - Submit a pull request against
main
Part of the KaririCode Framework ecosystem.
Built with ❤️ by Walmir Silva · kariricode.org