Skip to main content Link Search Menu Expand Document (external link)

Usage

Table of contents

  1. Using Inheritance
    1. Single Value Object
    2. Single Immutable Value Object
  2. Using Composition
    1. Single Value Object
    2. Single Immutable Value Object
  3. Accessing value
  4. Mutating value

There are different ways of using this package which will be outlined further down. Choose whatever suits your needs better.

Using Inheritance

The most simple way to use the package is by extending the SingleValueObject or SingleImmutableValueObject classes:

Single Value Object

use NorseBlue\ValueObjects\SingleValueObject;

class MyObject extends SingleValueObject
{
}

Single Immutable Value Object

use NorseBlue\ValueObjects\SingleImmutableValueObject;

class MyObject extends SingleImmutableValueObject
{
}

In both cases the isValid method should be implemented within your class.

See complete example

Using Composition

If you prefer composition over inheritance, you can use the provided traits and contracts instead:

Single Value Object

use NorseBlue\ValueObjects\Contracts\SingleValueObject as SingleValueObjectContract;
use NorseBlue\ValueObjects\Traits\SingleValueObjectBehavior;

class MyObject implements SingleValueObjectContract
{
    use SingleValueObjectBehavior;
}

Single Immutable Value Object

use NorseBlue\ValueObjects\Contracts\SingleValueObject as SingleValueObjectContract;
use NorseBlue\ValueObjects\Traits\SingleImmutableValueObjectBehavior;

class MyObject implements SingleValueObjectContract
{
    use SingleImmutableValueObjectBehavior;
}

See complete example

Note: The SingleValueObject contract is not really needed because all implementation is in the trait, but it is encourage to also implement the contract to allow decoupling in your application.

Accessing value

The value can be accessed like any object property:

echo $my_object->value;

The value object has a __toString method already defined that casts the value to string.

Mutating value

The value can be mutated like any object property:

$my_object->value = 'new value';

An immutable value object will throw a ImmutableValueObjectException when trying to mutate the value.