Reputation: 137
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
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.
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.storePost
shouldn't change if we add more validation logic. In Laravel you can use FormValidation
for thisstorePost
shouldn't change if we decide to change DB vendor like going NoSQL.storePost
shouldnt change if we need to change the email layout. Laravel has Notification
for thatstorePost
shouldnt change. Laravel has API Resource
s for thatSo, 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