PHP code example of attributes-php / validation

1. Go to this page and download the library: Download attributes-php/validation 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/ */

    

attributes-php / validation example snippets




use function Attributes\Validation\validate;
use Attributes\Validation\BaseModel;

class User extends BaseModel
{
    public float|int $age;
    public ?DateTime $birthday;
}

$rawData = [
    'age' => 30,
    'birthday' => '1994-01-01T09:00:00+00:00',
];

$user = validate($rawData, new User());

var_dump($user->age);      // int(30)
var_dump($user->birthday); // object(DateTime) "1994-01-01 09:00:00.000000" (+00:00)



use function Attributes\Validation\call;
use function Attributes\Validation\validate;
use Attributes\Validation\BaseModel;
use Attributes\Validation\Fields\Sequence;
use Attributes\Validation\ModelConfigs;
use Attributes\Validation\Type;

#[ModelConfigs(strict: false)]
class Blog extends BaseModel
{
    public string $title;

    #[Sequence(Type::string)]
    public array $tags;

    public ?DateTime $publishedAt = null;
}

$blog = validate([
    'title' => 'Hello',
    'tags' => ['php', 'validation'],
    'publishedAt' => '2025-03-06T08:57:06+00:00',
], new Blog());

// Call any callable with validated models and injected dependencies
$result = call('registerBlog', $rawData, $dependencies);

use Attributes\Validation\Exceptions\ValidationException;

try {
    validate($rawData, new Blog());
} catch (ValidationException $e) {
    $e->getErrors();
    // [
    //     'title' => ['Field is 
bash
composer