MVC – Is It Good Practice to Call a Controller Function from Another Controller?

mvc

I'm having a case where I'm handling the logic of a search in one controller and I'm generating some data based on searches and returning as statistics.

Is a good practice calling a controller function from another controller? Or two controllers should never 'talk'?

Best Answer

This is rather strange, although the answer depends on the language/framework you use, since different languages/frameworks have different approaches of MVC.

In general, you won't use one controller from another one since:

  • Controllers usually return a result of a type intended to be used by the MVC framework. This result contains a lot of information you, as a caller, don't need (such as the name of the view), and doesn't always make it easy to get to the information you may be interested in (in your case the model, if I guess right).

  • Controllers are not easy to initialize from business code, since they often need some amount of information about the HTTP request and the context. All this information is expected to be passed by the MVC framework.

More importantly, if you need a bunch of search results in two controllers—one which shows the results to the end user, another one which generates statistics, simply put the search logic in your business layer (where it belongs to in the first place, by the way), and keep your controllers as small as possible.

The role of a controller, in MVC, is to orchestrate the process:

  • Get the relevant input from the request,
  • Delegate to validators the task of validating/sanitizing the input,
  • Call the relevant methods of business layer,
  • Give to MVC framework the resulting model and the view.

The role of a controller is not to deal with business logic.

Once code moved to business layer, you can then provide a search interface which can be reusable in a clear, straightforward way, unlike one controller being used from another.