Skip to content

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

License

Notifications You must be signed in to change notification settings

noahlvb/php-valueobject

Repository files navigation

PHP Value Object

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: