As an example, if we wanted to replicate the latestPosts query method in our PostRepository by using a Specification for an in-memory implementation, it would look like this:
namespace InfrastructurePersistenceInMemory;
use DomainModelPost;
interface InMemoryPostSpecification
{
/**
* @return boolean
*/
public function specifies(Post $aPost);
}
The in-memory implementation for the latestPosts behavior could look like this:
namespace InfrastructurePersistenceInMemory;
use DomainModelPost;
class InMemoryLatestPostSpecification
implements InMemoryPostSpecification
{
private $since;
public function __construct(DateTimeImmutable $since)
{
$this->since = $since;
}
public function specifies(Post $aPost)
{
return $aPost->createdAt() > $this->since;
}
}
The query method for our Repository implementation could look like this:
class InMemoryPostRepository implements PostRepository
{
// ...
/**
* @param InMemoryPostSpecification $specification
*
* @return Post[]
*/
public function query($specification)
{
return $this->filterPosts(
function (Post $post) use($specification) {
return $specification->specifies($post);
}
);
}
}
Retrieving all the latest posts from the Repository is as simple as creating a tailored instance of the above implementation:
$latestPosts = $postRepository->query(
new InMemoryLatestPostSpecification(new DateTimeImmutable('-24'))
);