I have 3 ARs:
- Student
- Guardian
Business Rule:
- Student should have at least 1 authorized Guardian Entities should not be in an invalid state right?
Right now I enforced the invariant in my Student
constructor:
public function __construct(StudentId $id, Name $name, Guardian ...$guardians) {
if ( $this->hasNoAuthorizedGuardian(...$guardians) ) {
throw new NoAuthorizedGuardianException();
}
// initialized fields
}
However, while creating the repository part for my Student AR, I encountered a problem of fetching the "required" guardians for it.
class StudentRepository {
public function getById(StudentId $id): Student {
// other lines omitted for brevity
return new Student($id, $name, ...$guardians);
}
}
I came up with these questions in mind:
Should I reference
GuardianRepository
insideStudentRepository
? I feel like the answer is no, but I'm new to DDD so it might be validShould ARs be allowed to have reference to Repositories instead? I feel like the answer to this is also no, but like I said I'm new to DDD so this might be valid.
Did I enforce my invariant properly? Or should I put it in Domain Service so that I don't need to fetch the related entities in a single Repository?
Doing the second approach will let me do this:
class StudentService {
public function getById(StudentId $id) {
$student = $this->studentRepo->getById($id);
$guardians = $this->guardianRepo->getByStudentId($id);
$student->guardians(...$guardians);
return $student;
}
}
Cons of doing that though is my entities will become an Anemic Domain Entity since I transferred the invariant to another layer.
Another possible solution I came up with is Lazy Loading but I'm not sure how to do that including when and how to fetch the related entities.
TL;DR: If your root entity requires a reference to another root entity, how can you get it?
EDIT:
For clarification, I did not mention that Guardian has its own entities like Contacts and some other Value Objects. I think it's enough for it to be considered an AR because it should be the one that manage them.
Student-Guardian reference here is a Bounded Context I guess that I just learned now.