PHP code example of fsubal / donphan

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

    

fsubal / donphan example snippets




$user = [
    'user_id' => validateInt($_POST['user_id']),
    'name' => validateString($_POST['name']),
];

...

function doSomethingForUser(array $user)
{
    $name = $user['name'];
    ...
}



final class User
{
    use \Donphan\Immutable;

    const REQUIRED = [
        'user_id' => 'numeric',
        'name' => 'string'
    ];
}

// and then
$user = User::from([
    'user_id' => $_POST['user_id'],
    'name' => $_POST['name']
]);

function doSomethingForUser(User $user)
{
    $name = $user->name;
    ...
}

final class User
{
    use \Donphan\Immutable;

    const REQUIRED = [
        'user_id' => 'numeric',
        'name' => 'string',
        'birthday' => '\DateTimeImmutable'
    ];

    const OPTIONAL = [
        'url' => 'string'
    ];

    public static function beforeTypeCheck(array $params)
    {
        if (!isset($params['url'])) {
            $params['url'] = 'https://example.com';
        }
        return $params;
    }

    public static function afterTypeCheck(array $params)
    {
        if (strlen($params['name']) == 0) {
            throw new \InvalidArgumentException('params[name] must not be empty!');
        }
    }
}