Pregunta

I already asked a question about this answer on another topic, but I kind of got very interested to learn from it, so I have another doubt now. In particular, I was looking at the authenticate method, and the data mapper fetch method. I also found this answer as extremely helpful on this topic where the fetch method is kind of explained, but it is skipped the part where I am in doubt. The user tereško that answers this questions, on couple of occasions suggests that the methods in the data mapper should not be fetchById, fetchByUsername, etc., but rather one fetch method. My question is how am I going to fetch something specific as the methods I wrote, having only the domain object at hand?

For example, if I have a register service method where I need to check and possibly store username, password and email, I would need to fetch by username to check whether the user already exists, and after that to fetch by email to check whether that email is in the database already. So, how do I know in the fetch method what to do if I only have:

$mapper->fetch($object);

Do I possibly set fetch options on the domain object?

$account->setFetchOptions(['username']);

And then in the fetch method I would check and fetch. Does this makes sense? If someone has another idea, share it.

¿Fue útil?

Solución

I was in the exact same position as you not so long ago so I will answer this on my experience and how I am currently solving this problem.

I have experimented with the implementation you showed above, creating a domain object, setting the values and then passing the object into the fetch method. I found it to be very verbose so I came up with a new way. Basically if you have a Mappers\User you pass an Entities\User into it on construction. When the mapper is mapping data to the domain object it simple clones the injected Entities\User object it holds, sets the data and returns the newly cloned object so I can have the API like this:

public function fetchById($id);

You should look into the repository pattern for dealing with more complicated queries than fetching by an ID. It gives you a wide API for fetching an object or collections of objects in a variety of ways.

So you could have your Repositories\User with

public function fetchByUsername($username);

public function fetchByEmailAddress($emailAddress);

How you implement the internals of the repository is up to you there are many different takes on it like with most programming patterns. Your Repositories\User could hold your Mappers\User so when you fetch the user by the username for example you just use the mapper within the repository to map the data and return the user. All this is encapsulated by the repositories public interface.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top