1

Lets say that i have an aggregate root named User the user can have multiple Vehicle, the Vehicle entity has types such as (suv, truck, sedan, etc ...).

In that case if i want to get the User vehicles of type sedan only do i have to design my aggregate to get the sedans directly from the aggregate like User->getSedans() ?

Or can i get that throw the UserRepository->getVehiclesOfTypeSedan() and the aggregates only hold the Vehicles ?

AboElzooz
  • 309
  • 4
  • 16
  • 1
    The first question you have to ask is why your `User` aggregate has a collection of vehicles. What invariants are you trying to enforce with the large `User` cluster? You might say uniqueness, but we can usually leave that constraint to the database so it isin't an invariant that justifies holding a collection. You should strongly consider having an `owner` on the `Vehicule` which just references the `id` of the `User`. Then, getting vehicules would look like `vehiculeRepository.ofOwnerAndType(ownerId, VehiculeType.Sedan)`. – plalx May 03 '15 at 12:36
  • Also, depending on your domain you might want to reconsider naming an aggregate root `User`. There are usually more suitable names in most domains (e.g. `Client`). – plalx May 03 '15 at 12:40

1 Answers1

0

To keep your interface and inheritance hand in hand, I think it is better to separate your logic:

UserRepository->getVehicles("sedan");

Or you can utilize method-chaining:

UserRepository->getVehicles()->sedan;

In the above code, getVehicles(), returns a collection object which has NOT a property named sedan. You have to use php __get() to do the operation. Why then I do this? Because if you were able to fetch the cars by type though a property (remember properties are not functions, there is no execution), then it literally means that you have fetches all types and have them ready:

WRONG WAY AND MEMORY-KILLER APPROACH is that you fetch all of the user's car and put each type in its associated property.

Better way is returning an object, the object then is shipped with a function __get() to be invoked on each property retrieval:

$object->sedan;

sedan does not exist, so you have already predicted that:

function __get($param)
{
   $this->__getByType($param);
}

Though I prefer my very first suggestion.

Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105