MVC Architecture – Determining the Number of Controllers Needed

design-patternsmvcprogramming practicesweb-development

I have been coding for a while, but mostly scripts and simple applications. I've moved into a new role where it is all about developing Web Apps and using a proper MVC architecture, so I am desperately trying to learn about all that very quickly.

I hope this question is not too similar to "Best Practices for MVC Architecture" but as I am going through a few different tutorials, I noticed that some have multiple controllers for different things.

How many controllers does a single web app need?

I realize this would be difficult to answer without an example so I'll provide one:

Application:

  1. User logs in.
  2. User can do one of three things:
    a) Upload a file (stored in a mongodb database with meta data).
    b) Search for a file.
    c) Log out.

My question is a general one, but I gave the example to help out anyone trying to answer.

Best Answer

For your example I would create two controllers:

  • Sessions Controller for Login and Logout (create and destroy session for REST like layout)
  • Files Controller for everything on files (index=search and create=upload)

In general a RESTful approach where you think about everything as a resource that can be displayed, created, edited and destroyed gives you a good idea how to structure things. As you can see from my examples I don't stick too close to every single verb in REST.

You would most likely need more controllers for further functionality. For example a Users Controller where users can create new accounts. And in addition to this you would need an admin interface where you can edit the resources with higher privileges. In such a case it is quite common to have nearly every controller duplicated.

A very very rough estimate to get an initial idea could be one controller for every table in your database that users can access. But this is really only a very crude measurement.

Related Topic