0

I'm working with an MVC framework to build a simple Q&A web app, and I am trying to grasp the idea of controllers acting on the app.

For instance, say I have a home page with the following links:

  • Home > Login > Home > Profile
  • Home > List of questions (updated dynamically) > (new view showing) One question
  • Home > List of top answerers (updated dynamically)

In this case, would it make sense to have two controllers, namely - QuestionsController: to bring recent questions from Question model - UsersController: to help login and bring top-answerers from User model

I did some research and found out that I could use a SessionsController for the login/logout. Of course, the main ApplicationController is there too. Then for this view alone, there seem to be 4 controllers working... Is this decent practice?

  • You may want to specify what framework this is. For example, C# ASP.Net MVC would answer this question differently than AngularJS – brhardwick Jun 6 '17 at 11:42
  • @brhardwick I'm using Rails. Would this change anything? :) – sofarsophie Jun 7 '17 at 1:53
3

Coming from a guy who has built several applications in AngularJS, I'd say it is common to have multiple controllers working at any given time.

For example, Routers such as UI-Router allow you to define your different application screens (states) as a group of views, each view with its own controller.

The benefits are quite substantial - off the top of my head:

  1. Separation of concerns. While your current screen provides several different features, each controller governs its own area of responsibility. In your example, a controller for questions, one for answers, one for the session and one for navigation etc.

  2. Scalability. It will keep your code fragmented instead of all in one place, when your UI controller class starts creeping up to 500+ lines of code, you will start struggling.

  3. Code reuseability (DRY). If I navigate to a different screen, I can mix and match existing controllers and reuse some. For example, if I navigate to a FAQ section, I'll still need a controller for the navbar and footer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.