PHP code example of lbacik / value-object

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

    

lbacik / value-object example snippets


declare(strict_types=1);

use Sushi\ValueObject\Invariant;
use Sushi\ValueObject;

use function PHPUnit\Framework\assertGreaterThanOrEqual;
use function PHPUnit\Framework\assertIsInt;
use function PHPUnit\Framework\assertIsString;

class ExampleValueObject extends ValueObject
{
    private const NAME_MIN_LENGTH = 4;

    public function __construct(
        public readonly string $name,
        public readonly int $age
    ) {
        parent::__construct();
    }

    #[Invariant]
    protected function validateName(): void
    {
        assertGreaterThanOrEqual(self::NAME_MIN_LENGTH, mb_strlen($this->name));
    }

    #[Invariant]
    protected function validateAge(): void
    {
        assertIsInt($this->age);
        assertGreaterThanOrEqual(0, $this->age);
    }
}

$valueObjectOne = new ExampleValueObject(name: "FooBar", age: 30);