PHP code example of xdevmafia / php-value-object

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

    

xdevmafia / php-value-object example snippets


use XDM\ValueObject\Object\EmailObject;
use XDM\ValueObject\Type\StringType;

class User
{
    private StringType $username;
    private EmailObject $email;
    
    public function __construct(StringType $username, EmailObject $email)
    {
        $this->username = $username;
        $this->email = $email;
    }

    public function getUsername(): StringType
    {
        return $this->username;
    }

    public function setUsername(StringType $username): void
    {
        $this->username = $username;
    }

    public function getEmail(): EmailObject
    {
        return $this->email;
    }

    public function setEmail(EmailObject $email): void
    {
        $this->email = $email;
    }
}

try {
    $username = new StringType('xdevmafia');
    $email = new EmailObject('[email protected]');
} catch (ConstraintException $e) {
    throw $e;
}

$user = new User($username, $email);

use XDM\ValueObject\Constraint\Email;
use XDM\ValueObject\Type\StringType;

class EmailObject extends StringType
{
    protected function setConstraints(): void
    {
        $this->addConstraint(new Email());
    }
}

namespace App\ValueObject;

use XDM\ValueObject\Type\StringType;

class DeliveryAddressObject extends StringType
{
}

use XDM\ValueObject\Constraint\Regex;
use XDM\ValueObject\Type\StringType;

class UsernameObject extends StringType
{
    protected function setConstraints(): void
    {
        $this->addConstraint(new Regex('[a-z]{3,10}'));
    }
}

namespace App\Constraint;

use XDM\ValueObject\Constraint;

class HexColor implements Constraint
{
    public function __invoke($value): bool
    {
        return ctype_xdigit($value);
    }
}

namespace App\ValueObject;

use App\Constraint\HexColor;
use XDM\ValueObject\Type\StringType;

class ColorObject extends StringType
{
    protected function setConstraints(): void
    {
        $this->addConstraint(new HexColor());
    }
}