noahlvb/valueobject

A php library to bootstrap the use of Domain Driven Design valueObjects

v1.0.2 2022-04-30 19:51 UTC

This package is auto-updated.

Last update: 2025-03-01 00:30:38 UTC


README

A library to bootstrap the use of Domain Driven Design valueObjects

CI Latest Stable Version License

Installation

With composer, add:

$ composer require noahlvb/valueobject

Or if your using Symfony: valueobject-bundle

$ composer require noahlvb/valueobject-bundle

Run Tests

To make sure everything works you can run tests:

$ make test

How to use

Currently there are two primitive types supported:

  • String : ValueObjectString
  • Integer : ValueObjectInteger

Creating a simple value object without checks.

class Name extends ValueObjectString
{
    protected function sanitize(string $value): string
    {
        return trim($value);
    }

    public function isValid(string $value): bool
    {
        return true;
    }
}

If you want to validate a value during construction of a value object, simply override the isValid method with your check:

class Name extends ValueObject
{
    protected function sanitize(string $value): string
    {
        return trim($value);
    }

    public function isValid(string $value): bool
    {
        return strlen($value) < 255;
    }
}

If you want a custom exception thrown during construction, override the getException method with your own exception:

class Name extends ValueObject
{
    protected function sanitize(string $value): string
    {
        return trim($value);
    }

    public function isValid(string $value): bool
    {
        return strlen($value) < 255;
    }

    protected function getException(): Exception
    {
        return new NameToLongException();
    }
}

Examples

Example implementations can be found at tests/Unit/ValueObject. These are the same value objects used for testing: