PHP code example of wiz-develop / php-value-object

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

    

wiz-develop / php-value-object example snippets


use WizDevelop\PhpValueObject\Boolean\BooleanValue;
use WizDevelop\PhpMonad\Result;

// 直接作成 - 検証なし
$bool = BooleanValue::from(true);

// 検証付き作成 - Result型を返す
$result = BooleanValue::tryFrom(true);
if ($result->isOk()) {
    $bool = $result->unwrap();
} else {
    $error = $result->unwrapErr(); // エラー情報を取得
}

// 等価性の比較
$anotherBool = BooleanValue::from(true);
$areEqual = $bool->equals($anotherBool); // true

use WizDevelop\PhpValueObject\String\StringValue;
use WizDevelop\PhpValueObject\String\EmailAddress;
use WizDevelop\PhpValueObject\String\Ulid;

// 基本的な文字列
$str = StringValue::from("Hello, World!");
echo $str; // 文字列への自動変換

// メールアドレス - 検証付き
$emailResult = EmailAddress::tryFrom("[email protected]");
if ($emailResult->isOk()) {
    $email = $emailResult->unwrap();
}

// ULID
$ulid = Ulid::generate(); // 新しいULIDを生成

use WizDevelop\PhpValueObject\Number\IntegerValue;
use WizDevelop\PhpValueObject\Number\PositiveIntegerValue;
use WizDevelop\PhpValueObject\Number\DecimalValue;
use BcMath\Number;

// 整数値
$int = IntegerValue::from(42);

// 正の整数値 - 0未満の値は検証エラー
$positiveInt = PositiveIntegerValue::tryFrom(10);

// 少数値(BCMath を利用した高精度計算)
$decimal = DecimalValue::from(new Number("3.14159"));

// 算術演算 (DecimalValueの場合)
$pi = DecimalValue::from(new Number("3.14159"));
$radius = DecimalValue::from(new Number("5"));
$area = $pi->multiply($radius->square()); // πr²

use WizDevelop\PhpValueObject\DateTime\LocalDate;
use WizDevelop\PhpValueObject\DateTime\LocalTime;
use WizDevelop\PhpValueObject\DateTime\LocalDateTime;
use DateTimeImmutable;
use DateTimeZone;

// 日付
$date = LocalDate::of(2025, 5, 14);
$tomorrow = $date->addDays(1);

// 時刻
$time = LocalTime::of(13, 30, 0);
$laterTime = $time->addHours(2);

// 日時
$dateTime = LocalDateTime::of($date, $time);

// 現在時刻からの作成
$now = LocalDateTime::now(new DateTimeZone('Asia/Tokyo'));

// DateTimeImmutableとの相互変換
$nativeDate = $dateTime->toDateTimeImmutable();
$backToLocalDateTime = LocalDateTime::from($nativeDate);

// 日付の比較
$isBefore = $date->isBefore($tomorrow); // true

use WizDevelop\PhpValueObject\Collection\ArrayList;
use WizDevelop\PhpValueObject\Collection\Map;
use WizDevelop\PhpValueObject\Collection\Pair;
use WizDevelop\PhpValueObject\ValueObjectList;
use WizDevelop\PhpValueObject\String\StringValue;

// ArrayList - 不変のリスト
$list = ArrayList::from([1, 2, 3, 4, 5]);
$filteredList = $list->filter(fn($value) => $value > 2); // [3, 4, 5]
$mappedList = $list->map(fn($value) => $value * 2); // [2, 4, 6, 8, 10]
$sortedList = $list->sort(fn($a, $b) => $b <=> $a); // [5, 4, 3, 2, 1]
$concatList = $list->concat(ArrayList::from([6, 7, 8])); // [1, 2, 3, 4, 5, 6, 7, 8]

// Map - キーと値のペアを扱う不変のマップ
$map = Map::make(['name' => 'John', 'age' => 30]);
$hasKey = $map->has('name'); // true
$values = $map->values(); // ArrayList::from(['John', 30])
$keys = $map->keys(); // ArrayList::from(['name', 'age'])
$filteredMap = $map->filter(fn($value) => is_string($value)); // ['name' => 'John']
$updatedMap = $map->put('age', 31); // ['name' => 'John', 'age' => 31]

// Pair - キーと値のペア
$pair = Pair::of('key', 'value');
echo $pair->key; // 'key'
echo $pair->value; // 'value'

// 値オブジェクトのリスト
$stringList = ArrayList::from([
    StringValue::from('apple'),
    StringValue::from('banana'),
    StringValue::from('orange')
]);
// ValueObjectListへの変換 - 値オブジェクトの等価性に基づいた操作をサポート
$valueObjectList = new ValueObjectList($stringList->toArray());
$hasApple = $valueObjectList->has(StringValue::from('apple')); // true

use Override;
use WizDevelop\PhpValueObject\String\StringValue;
use WizDevelop\PhpValueObject\ValueObjectMeta;

#[ValueObjectMeta(name: '商品コード')]
final readonly class ProductCode extends StringValue
{
    #[Override]
    final public static function minLength(): int
    {
        return 5;
    }

    #[Override]
    final public static function maxLength(): int
    {
        return 5;
    }

    #[Override]
    final protected static function regex(): string
    {
        return '/^P[0-9]{4}$/';
    }
}