1
\$\begingroup\$

I have a get route to show the data for a chat with another user. If an existing chat exists I want to return that, otherwise create a new chat and return it.

/chat/user/{contra_user_id}

Should my Service or my repository be adding chat members to the chat? Currently I have my service creating each member.

class ChatService
{
    private $chatRepository;

    public function __construct(ChatRepository $chatRepository)
    {
        $this->chatRepository = $chatRepository;
    }

    public function findByUsers(User $user, User $contraUser) : Collection
    {
        $chat = $this->chatRepository->findByUsers($user, $contraUser);
        if ($chat = $chat->first()) {
            return $chat;
        }

        $chat = $this->chatRepository->create();
        $member = $this->chatMemberRepository->create($chat, $user);
        $contraMember = $this->chatMemberRepository->create($chat, $user);
        $returnChat = $this->chatRepository->find($chat->id);

        return $returnChat;
    }
}
\$\endgroup\$
2
\$\begingroup\$

You can break the functionality in to 2 seperate methods to make it more reusable. Here, findChatByUsers could return a collection or null, so the type hint was removed.

public function findChatByUsers(User $user, User $contraUser)
{
    $chat = $this->chatRepository
        ->findByUsers($user, $contraUser)
        ->first();

    return $chat;
}

public function getChat(User $user, User $contraUser) : Collection
{
    $chat = $this->findChatByUsers($user, $contraUser);

    // If chat is not available, create new chat
    if (!$chat) {
        $chat = $this->chatRepository->create();
        $member = $this->chatMemberRepository->create($chat, $user);
        $contraMember = $this->chatMemberRepository->create($chat, $user);
        $chat = $this->chatRepository->find($chat->id);
    }

    return $chat;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.