1. Go to this page and download the library: Download morebec/value-objects library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
morebec / value-objects example snippets
use Assert\Assertion;
use Morebec\ValueObjects\ValueObjectInterface;
/**
* Age Value Object
*/
final class Age implements ValueObjectInterface
{
/** @var int age */
private $age;
public function __construct(int $age)
{
Assertion::min($age, 1);
$this->age = $age;
}
public function __toString()
{
return strval($this->age);
}
/**
* Returns the value of this age object
* @return int
*/
public function toInt(): int
{
return $this->age;
}
/**
* Indicates if this value object is equal to abother value object
* @param ValueObjectInterface $valueObject othervalue object to compare to
* @return boolean true if equal otherwise false
*/
public function isEqualTo(ValueObjectInterface $vo): bool
{
return (string)$this === (string)$vo;
}
}
$age = new Age(24);
// Test Equality
$maturity = new Age(18);
$age->isEqualTo($maturity); // false
$age == $maturity; // false
$age === '18'; // false
// Test Greater than
$age->toInt() >= 18; // true
$age->toInt() >= $maturity->toInt();
use Morebec\ValueObjects\ValueObjectInterface;
/**
* CardinalPoint
*/
class CardinalPoint implements ValueObjectInterface
{
const NORTH = 'NORTH';
const EAST = 'EAST';
const WEST = 'WEST';
const SOUTH = 'SOUTH';
}
// Instatiate a new CardinalPoint instance
$direction = new CardinalPoint(CardinalPoint::NORTH);
// Since Enums have builtin validation,
// the following line would throw an InvalidArgumentException:
$direction = new CardinalPoint('North');
// However the following would work:
$direction = new CardinalPoint('NORTH');
// Using in functions or class methods
public function changeDirection(CardinalPoint $direction)
{
// Testing equlity with string
if(!$direction->isEqualTo(new CardinalPoint(CardinalPoint::EAST))) {
echo 'Not going East!';
}
// Since the constants are strings, it is also possible to compare
// using string comparison
if($direction == CardinalPoint::NORTH) {
echo 'Definitely going North!';
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.