/** * This is a perfect example of a value object that is identifiable by it's value alone and * is guaranteed to be valid each time an instance is created. Another important property of value objects * is immutability. * * Notice also the use of a named constructor (fromInt) which adds a little context when creating an instance. */ classPostId { privateint $id;
/** * Like PostId, this is a value object which holds the value of the current status of a Post. It can be constructed * either from a string or int and is able to validate itself. An instance can then be converted back to int or string. */ classPostStatus { const STATE_DRAFT_ID = 1; const STATE_PUBLISHED_ID = 2;
/** * there is a reason that I avoid using __toString() as it operates outside of the stack in PHP * and is therefor not able to operate well with exceptions */ publicfunctiontoString(): string { return$this->name; }
privatestaticfunctionensureIsValidId(int $status) { if (!in_array($status, array_keys(self::$validStates), true)) { thrownewInvalidArgumentException('Invalid status id given'); } }
privatestaticfunctionensureIsValidName(string $status) { if (!in_array($status, self::$validStates, true)) { thrownewInvalidArgumentException('Invalid status name given'); } } }
/** * This class is situated between Entity layer (class Post) and access object layer (Persistence). * * Repository encapsulates the set of objects persisted in a data store and the operations performed over them * providing a more object-oriented view of the persistence layer * * Repository also supports the objective of achieving a clean separation and one-way dependency * between the domain and data mapping layers */ classPostRepository { private Persistence $persistence;
publicfunctionfindById(PostId $id): Post { try { $arrayData = $this->persistence->retrieve($id->toInt()); } catch (OutOfBoundsException $e) { thrownewOutOfBoundsException(sprintf('Post with id %d does not exist', $id->toInt()), 0, $e); }
publicfunctiontestThrowsExceptionWhenTryingToFindPostWhichDoesNotExist() { $this->expectException(OutOfBoundsException::class); $this->expectExceptionMessage('Post with id 42 does not exist');