, (*1)
Equalable
The equalable library provides a single interface that defines a method
that implementing classes can use to provide custom equality determination.
This is useful for value objects and entities alike, since the former might
want to allow equality checks against scalar types, and the latter need to
exclude all encapsulated values from the equality determination which are not
part of their identity defining values., (*2)
Installation
Open a terminal, enter your project directory and execute the following command
to add this package to your dependencies:, (*3)
composer require fleshgrinder/equalable
This command requires you to have Composer installed globally, as explained in
the installation chapter of the
Composer documentation., (*4)
Usage
Simply implement the interface and the required equals
method. The actual
implementation of the methodâs body depends on the use-case. Value objects
for instance might want to allow equality checks against scalar types, e.g.:, (*5)
final class UserId implements Equalable {
private $uid;
// ...
public function equals($other): bool {
if ($other instanceof $this) {
$other = $other->uid;
}
return \is_int($other) && $this->uid === $other;
}
}
Entities on the other hand want to exclude all encapsulated values which are
not part of their identity defining values from the determination, e.g.:, (*6)
final class User implements Equalable {
private $uid;
private $name;
private $email;
// ...
public function equals($other): bool {
return $other instanceof $this && $this->uid->equals($other->uid);
}
}
Testing
There are not tests since this library provides a single interface, which
obviously has no implementation., (*7)