PHP code example of thesameson / php-data-contracts

1. Go to this page and download the library: Download thesameson/php-data-contracts library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

thesameson / php-data-contracts example snippets


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', 

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 "

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