Abbas
Abbas

Reputation: 137

how to implement Single Responsibility in laravel

I am so confused about how to implement and how to follow SRP (single responsibility principle ) in a Laravel controller.

Suppose we have a controller which we have to do these things:

e.g

    public function StorePost() {
        // check user login()
        //check number of current user Post count =>which must be less than 10
        //store post
        //send an email to user which your post has saved
        //return =>api:json /web : redirect
    }

I know that I can implement some DB queries in the repository but I don't know how to implement others of my logic code to achieve SRP

Also, I know there is a Heyman package to achieve these but I want to implement it by myself.

Upvotes: 0

Views: 1198

Answers (1)

Sakibul Alam
Sakibul Alam

Reputation: 1823

SRP in this context basically means each class and method should only be responsible for a single behaviour/feature. A rule of thumb is a class or method should change for one reason only, if it changes for multiple reasons, it needs to be broken down into smaller parts.

  • Your storePost method should not bother with checking the user login, that should be handled elsewhere before invoking storePost. storePost shouldnt change if the auth mechanism changes like switching from api token to json web token or something else. Laravel does this in the middleware level with the auth middleware.
  • Checking the users post count, this can be checked in the validation stage. storePost shouldn't change if we add more validation logic. In Laravel you can use FormValidation for this
  • For storing the post, the controller doesn't need to know how to call the DB, you can use the active record style using the model class or maybe create a service or repository class if your use case requires that. storePost shouldn't change if we decide to change DB vendor like going NoSQL.
  • For sending email, again the controller doesnt need to know how to send the email like what the subject/body recipients are. storePost shouldnt change if we need to change the email layout. Laravel has Notification for that
  • For serialising the response to json, the controller doesnt need to know how to format the response. if we decide to update how our json looks, storePost shouldnt change. Laravel has API Resources for that

So, ultimately in this example, the responsibility of the controller method is basically to glue all these together. It basically does what you wrote down, it only responsible for maintaining the step by step behavior, everything else is delegated to someone else. if the behavior change, like adding new behavior e.g notify all follower, storePost will change.

Upvotes: 1

Related Questions