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 Resource
s 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.