Skip to content

Repository files navigation

PHP Value Objects SDK

Build Status

Author: Laurens Hellemons lhellemons@gmail.com

This library contains utility classes, traits and interfaces for working with value objects in PHP. By using these, you can easily define your own value objects.

Read the full documentation here.

Why value objects?

Value objects are a core component of domain-driven design (DDD). They are objects that do not have an identity, and are instead defined by their values. Any large system that deals with domain concepts will eventually develop a need to model some of these concepts as value objects. Examples of such concepts include

  • Dates
  • Amounts of money
  • Coordinates
  • Adresses
  • Physical quantities such as age, length or weight

This library helps circumvent PHP's limited support for value objects. Using the classes, interfaces and traits provided by this package, you can create your own value objects without worrying about the internals.

Usage

Install the package using composer.

composer require lhellemons/php-value-objects

Then, use the classes or traits in your own designs.

<?phpuseSolidPhp\ValueObjects\Enum\EnumTrait;
finalclass Weekday
{
use EnumTrait;
publicstaticfunctionMONDAY(): self
{
returnself::define('MONDAY');
}
publicstaticfunctionTUESDAY(): self
{
returnself::define('TUESDAY');
}
// ...
}
// ...$monday = Weekday::MONDAY();
$tuesday = Weekday::TUESDAY();
$deliveryDay = WeekDay::MONDAY();
$monday === $deliveryDay; // true$monday === $tuesday; // false
useSolidPhp\ValueObjects\Value\ValueObjectTrait;
finalclass EmailAddress
{
use ValueObjectTrait;
/** @var string */private$emailAddressString;
privatefunction__construct(string$emailAddressString)
{
$this->emailAddressString = $emailAddressString;
}
publicfunctionof(string$emailAddressString): self
{
$normalizedString = strtolower(trim($emailAddressString));
returnstatic::getInstance($normalizedString);
}
publicfunctiongetString(): string
{
return$this->emailAddressString;
}
}
// ...$emailAddress = EmailAddress::of("annie@email.com");
$sameEmailAddress = EmailAddress::of(" ANNIE@EMAIL.COM");
$emailAddress === $sameEmailAddress; // true

About

Value object SDK for PHP

Resources

Stars

2 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages