I'm trying to implement some domain driven design architecture, such as a repository to talk to the database, and a service that talks to the repository.
I have an action where I want to see if a User exists, and if he does, update his data, if he doesn't, create it and then perform a task (this could be done using event listeners but I'm not there yet).
- Now I'm wondering if my service method can do all these things? Is there another actor that should be responsible for this?
- This method is not very testable, since it's performing multiple actions? How would I test a method like this?
public function updateOrCreate($data)
{
$userData = static::getUserDataFromAccessToken($data);
// Find the user
$user = $this->userRepository->find($userData['id']);
// If we found the user, update and return
if ($user) {
$this->userRepository->update($userData);
// Return the updated user
return $this->userRepository->find($userData['id']);
}
// Else create
$created = $this->userRepository->create($userData);
if ($created) {
// Get the newly created user
$user = $this->userRepository->find($userData['id']);
// Get the activities
$this->activityTask->perform($user);
return $user;
}
}
public static function getUserDataFromAccessToken($token): array
{
return [
'id' => $token->getValues()['athlete']['id'],
'username' => $token->getValues()['athlete']['username'],
'photo' => $token->getValues()['athlete']['profile'],
'access_token' => $token->getToken(),
'refresh_token' => $token->getRefreshToken(),
];
}
$token->getValues()
as a variable and use it multiple times instead of calling the method three times to populate the return array. We must never ask the system to fetch the same unchanged data more than once. Or (I don't know what else is in theathlete
column), you might merge the return value ofarray_column($token->getValues(), 'athlete')
. \$\endgroup\$getUserDataFromAccessToken
. It's easier to deal with models than it is with repositories, since that removes a need for re fetch of data after you perform and update. Also, why would user creation fail? \$\endgroup\$