PHPackages                             thesameson/php-data-contracts - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [PSR &amp; Standards](/categories/psr-standards)
4. /
5. thesameson/php-data-contracts

ActiveLibrary[PSR &amp; Standards](/categories/psr-standards)

thesameson/php-data-contracts
=============================

Extensible PHP library for defining and serializing Data Contracts. Supports PHP Attributes, custom resolvers, and runtime enrichment. Ships with Open Data Contract Standard (ODCS) support, extensible for custom standards.

0.1.0(4mo ago)01MITPHPPHP ^8.2

Since Feb 15Pushed 4mo agoCompare

[ Source](https://github.com/thesameson/php-data-contracts)[ Packagist](https://packagist.org/packages/thesameson/php-data-contracts)[ RSS](/packages/thesameson-php-data-contracts/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (4)Versions (3)Used By (0)

PHP Data Contracts
==================

[](#php-data-contracts)

Extensible PHP library for defining and serializing Data Contracts using PHP Attributes or programmatically at runtime. Ships with [Open Data Contract Standard (ODCS)](https://bitol-io.github.io/open-data-contract-standard/) support, extensible for custom standards.

> **Work in progress**The API is stabilizing but may still change.

Requirements
------------

[](#requirements)

- PHP 8.2+

Installation
------------

[](#installation)

```
composer require thesameson/php-data-contracts
```

Quick Start
-----------

[](#quick-start)

Annotate your classes with the package's attributes to export them as data contracts:

```
use DataContracts\Attribute\Contract;
use DataContracts\Attribute\Schema;
use DataContracts\Attribute\Field;
use DataContracts\ContractBuilder;

#[Contract('user-contract', version: '1.0.0', owner: 'data-team')]
#[Schema(name: 'Users', physicalName: 'users', physicalType: 'table')]
class User
{
    #[Field(description: 'Primary key', primaryKey: true)]
    public int $id;

    #[Field(description: 'User email', required: true, format: 'email', maxLength: 255)]
    public string $email;

    #[Field(logicalType: 'timestamp', required: true)]
    public string $createdAt;
}

$result = ContractBuilder::create('user-contract')
    ->addSource(User::class)
    ->toYaml('user-contract.yaml');
```

Advanced Usage
--------------

[](#advanced-usage)

The builder supports runtime enrichment and custom resolvers, all chainable:

```
use DataContracts\Config\ConfigurationBuilder;
use DataContracts\ContractBuilder;
use DataContracts\Extractor\Metadata\RawFieldMetadata;
use DataContracts\Model\Definition\ContractDefinition;
use DataContracts\Model\Definition\FieldDefinition;
use DataContracts\Resolver\Field\FieldResolverInterface;
use DataContracts\Resolver\Field\FieldResolutionResult;
use DataContracts\Resolver\ResolutionContext;

// Configuration: strict validation, alphabetical field ordering
$config = (new ConfigurationBuilder())
    ->strict()
    ->sortFieldsAlphabetically()
    ->build();

$result = ContractBuilder::create('user-contract', config: $config)
    ->addSource(User::class)

    // Add fields at runtime without modifying the source class
    ->addField('Users', 'updatedAt', function (FieldDefinition $field) {
        $field->setLogicalType('timestamp')
            ->setRequired(true);
    })

    // Enrichment: modify the contract/schema/field definition after extraction
    ->enrichContract(function (ContractDefinition $contract) {
        $contract->setDescription('User accounts and profile data');
        return $contract;
    })

    // Custom resolver: hook into the extraction pipeline (priority 100+)
    // This example marks all "id" fields as "required"
    ->addFieldResolver(new class implements FieldResolverInterface {
        public function getPriority(): int { return 100; }
        public function supports(RawFieldMetadata $raw, ResolutionContext $ctx): bool
        {
            return $raw->name === 'id' || str_ends_with($raw->name, '_id');
        }
        public function resolve(
            RawFieldMetadata $raw,
            FieldDefinition $current,
            ResolutionContext $ctx,
        ): FieldResolutionResult {
            $current->setRequired(true);
            return FieldResolutionResult::continue($current);
        }
    })

    ->toYaml();
```

ODCS Support
------------

[](#odcs-support)

The built-in ODCS implementation covers fundamental contract, schema, and field properties. For ODCS properties that aren't modeled internally (e.g., `classification`, `criticalDataElement`), use `customProperties` - they are spread as top-level keys in the output:

```
#[Field(
    logicalType: 'string',
    required: true,
    customProperties: [
        'classification' => 'sensitive',
        'criticalDataElement' => true,
    ],
)]
public string $email;
```

The same works programmatically via `setCustomProperties()` on any definition object, or at the schema/contract level through `#[Schema(customProperties: [...])]` and `#[Contract(customProperties: [...])]`.

Key Concepts
------------

[](#key-concepts)

ConceptDescription**Attributes**`#[Contract]`, `#[Schema]`, `#[Field]` declare metadata directly on PHP classes and properties**Resolvers**Transform raw extracted metadata into normalized definitions (e.g., physical -&gt; logical type mapping)**Enrichment**Runtime callbacks to add, modify, or remove fields/schemas after extraction**Standards**Pluggable output standards. ODCS ships built-in, implement `StandardInterface` for custom ones**Serializers**Output to YAML, JSON, or array or bring your own `SerializerInterface`License
-------

[](#license)

MIT

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance75

Regular maintenance activity

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

137d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/dac41d75d7d123bbaa8241c61c5356ff8740b4f69c749349317b2039a10b17f2?d=identicon)[thesameson](/maintainers/thesameson)

---

Top Contributors

[![thesameson](https://avatars.githubusercontent.com/u/4759367?v=4)](https://github.com/thesameson "thesameson (47 commits)")

---

Tags

schemayamlattributesdata-contractsodcs

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/thesameson-php-data-contracts/health.svg)

```
[![Health](https://phpackages.com/badges/thesameson-php-data-contracts/health.svg)](https://phpackages.com/packages/thesameson-php-data-contracts)
```

###  Alternatives

[craftcms/cms

Craft CMS

3.6k3.6M3.1k](/packages/craftcms-cms)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[rcsofttech/audit-trail-bundle

Enterprise-grade, high-performance Symfony audit trail bundle. Automatically track Doctrine entity changes with split-phase architecture, multiple transports (HTTP, Queue, Doctrine), and sensitive data masking.

1189.8k](/packages/rcsofttech-audit-trail-bundle)[friendsoftypo3/content-blocks

TYPO3 CMS Content Blocks - Content Types API | Define reusable components via YAML

103519.9k53](/packages/friendsoftypo3-content-blocks)[2lenet/crudit-bundle

The easy like Crud'it Bundle.

1616.4k14](/packages/2lenet-crudit-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
