How many Controllers should you have? [Laravel]

Controllers are the life and blood of a Laravel application. It’s impossible to imagine a framework without them (well, it is, but technically something has to receive the route action, and whether it’s a class or function, it becomes a controller, so to speak).

In the last 3-4 years of my development experience, I went through a minor transformation when it comes to the number of controllers in my application. Earlier, my reasoning was like this: “Controllers, well, control stuff; what they control are the business entities — customers, orders, sellers, etc.”.

So, it was natural to have one “controller” per entity, and the directory structure would look like this:

Controllers
 - UserController.php
 - CustomerController.php
 - SellerController.php
 - [ . . . ] 

Looks very pristine to the eye: all the controllers live inside an aptly-named directory, and all clearly demarcate their territory. Just like the number of figureheads in a system, the fewer the better, right?

The approach worked, but only as far as trivial projects like To-Do List were concerned. In any real-life system, an entity is involved in so many transactions that its controller ends up having a few dozen functions and hundreds of lines of code. Not pretty at all.

I then came across the approach that increases the number of controllers. Now my applications have 20, 30 or more controllers, depending on how many types of transactions every entity is involved in. And they’re into their separate directories. As a result, code organization becomes more sane, and the controllers becomes smaller and more DRY.

Here’s what my new structure looks like:

Controllers
- User
  - UserLoginController
  - UserProfileController
  - UserPurchaseController
- Admin
  - AdminAccountController
  - AdminTransactionController
[. . .]

There’s no limit to how deep you can go, but so far for me, one level deep is good enough.

Agree? Disagree? Do you have a better scheme? I’d love to hear your side. 🙂

Leave a Reply

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