PHP code example of phpgears / value-object

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

    

phpgears / value-object example snippets




use Gears\ValueObject\AbstractValueObject;

final class CustomStringValueObject extends AbstractValueObject
{
    private $value;

    public static function fromString(string $value)
    {
        $stringObject = new self();
        $stringObject->value = $value;

        return $stringObject;
    }

    public function getValue(): string
    {
        return $this->value;
    }

    public function isEqualTo($valueObject): bool
    {
        return \get_class($valueObject) === self::class 
            && $valueObject->getValue() === $this->value;
    }
}

use Gears\ValueObject\AbstractValueObject;

final class Money extends AbstractValueObject implements \Serializable
{
    private const CURRENCY_EUR = 'eur';

    private $value;
    private $precision;
    private $currency;

    public static function fromEuro(int $value, int $precision)
    {
        $money = new self();
        $money->value = $value;
        $money->precision = $precision;
        $money->currency = static::CURRENCY_EUR; // Should be an enum

        return $money;
    }

    // [...]

    final public function __serialize(): array
    {
        return [
            'value' => $this->value,
            'precision' => $this->precision,
            'currency' => $this->currency,
        ];
    }

    final public function __unserialize(array $data): void
    {
        $this->assertImmutable();

        $this->value = $data['value'];
        $this->precision = $data['precision'];
        $this->currency = $data['currency'];
    }

    final public function serialize(): string
    {
        return serialize([
            $this->value,
            $this->precision,
            $this->currency,
        ]);
    }

    public function unserialize($serialized): void 
    {
        $this->assertImmutable();

        list(
            $this->value,
            $this->precision,
            $this->currency
        ) = \unserialize($serialized, ['allowed_classes' => false]);
    }
}