Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More controllers but less actions or less controllers but more actions

What makes you determine to create a new controller instead of adding more actions to an existing controller? Where do you draw the line and WHY?

like image 425
Elisabeth Avatar asked Jun 23 '12 18:06

Elisabeth


People also ask

What does controller action mean?

An action (or action method) is a method on a controller which handles requests. Controllers logically group similar actions together. This aggregation of actions allows common sets of rules, such as routing, caching, and authorization, to be applied collectively. Requests are mapped to actions through routing.

Can a controller have multiple actions with same name?

MVC cannot have two actions with the same name.

Should each model have a controller?

You need a controller just when you have request actions on the relative model; When a model is just for data calculation and basic business logic implementation, don't generate the controller.


1 Answers

What certainly does not get into the picture is the number of actions¹ -- at least in the sense that "oh, I 'm over 50 actions in this controller, let's start another one".

The guideline² should be: controllers are a logical group for actions that operate on the same type of object (the same type of model might be a better definition). If it so happens that you have a model so rich in functionality that there are 30 separate actions that can be performed on it, go ahead and put them in the same controller.

On the other side of the coin: if you have simple models and you find yourself writing controllers with only a few actions each, that should be a reason to feel good about the maintainability of the application rather than a reason to worry.


Notes:

¹ Of course, a controller with that many actions is a red flag for possible code abuse so the number should come into consideration -- just not as some kind of hard rule.

² And it's really a guideline -- the aim here is to build a maintainable system, not to follow some religious scripture.

like image 52
Jon Avatar answered Oct 31 '22 05:10

Jon