0

I keep getting faced with the dilemma of making sure that my Controller isn't too bloated and only focuses on business logic. At the same time my classes should be conforming to SRP. A simple example as follows. When a User sends a message to another user, I do the following

  • Fetch the conversation and ensuring that the user is authorized.
  • Save the message
  • Send notification to the receiver
  • Logging for tracking purposes to know how many people are using our system.

So, if if I put all of that in the Controller, it will be as follows

public function store(Request $request) {

    $userId = Auth::check();
    $conversation = Conversation::fetch($userId, $request->post('conversationId');
    if (!$conversation) {
       abort(403);
    }
    $conversation->sendMessage($userId, $request->post('message'));
    Notification::sendMessageNotification($conversation->other_user_id);
    Track::sentMessage($conversation);

}

So my controller, is doing more than focusing on business logic, what's worse is any place I want to send the message, I have to copy and paste Notification and Track. Now, if I want to put Notification and Track in the Conversation class, I would be violating SRP since I'm doing more than the class should do.

  • Tracking very specifically feels like something that lends itself to [events](https://laravel.com/docs/10.x/events), and maybe notifications, too – Chris Haas May 28 '23 at 20:23

0 Answers0