Laravel: How many controllers are too many?

Laravel, Software / Friday, March 2nd, 2018

Recently, in a phone interview for a remote positions, this post of mine was called out by the interviewer. His comment was, more or less, that it was stupid to worry about the number of controller in an MVC application. He said that putting logic in controller is a very bad practice, and that I should have clear separation of concerns via the Repository pattern.

I agreed with him that day, but when I later thought about it, I realized there’s still a lot of value in having multiple controllers for a single entity. This may not be obvious in small applications, but consider a large system where one entity can do multiple actions, and each action has a sub-action. For instance, a Customer can buy, review, return, reject, a product, and so on.

Now also suppose that there are three ways of buying something, three of returning, two of rejecting, and so on. If you put all these functions inside a single controller, the controller becomes harder to reason about. I, for one, would definitely recoil if I saw 50 functions in a single class, even if everything is still being done by a repository.

In these cases, I don’t think dividing your controllers into, say, CustomerPurchaseController, CustomerReviewContoller ,etc., is a bad idea. The work is still being done by the Repository, but now I have a much easier time analyzing the code base.

Lesson? Don’t be quick to dismiss something that doesn’t agree with your experience. It might be useful in some cases.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.