I have a tree of Zone
objects:
class Zone {
protected Zone $parent;
public function __construct(Zone $parent) {
$this->parent = $parent;
}
}
There are no children
nor descendants
property in the Zone, because I want to avoid the pain of managing these relationships in the domain model.
Instead, a domain service maintains a closure table in the database, to map a zone to all its descendants, at any level.
Now, I have a User
which can be assigned one or more Zones:
class User {
protected array $zones;
public function assignZone(Zone $zone) {
$this->zones[] = $zone;
}
}
My problem is that, prior to assigning a new Zone to the User, I'd like to check that this Zone is not already assigned, either explicitly or implicitly via one of its descendants.
Therefore I'd like my controller to transiently inject the Service into this method, to perform the necessary checks:
class User {
protected array $zones;
public function assignZone(Zone $newZone, ZoneService $zoneService) {
foreach ($this->zones as $zone) {
if ($service->zoneHasDescendant($zone, $newZone)) {
throw new Exception('The user is already assigned this zone');
}
}
$this->zones[] = $zone;
}
}
Is that a good practice, or if not, what's the correct alternative?