22

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'?

24

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.

  • Hi, Thank you for your response. Assuming that I moved the search logic to business layer, where is the best place to put the search interface? I'm using Laravel. – IAmJulianAcosta Dec 3 '14 at 18:15
  • Unfortunately, I've never used Laravel. Moreover, I imagine that the answer will depend more on the architecture of your application, rather than the framework. – Arseni Mourzenko Dec 3 '14 at 18:32
  • Assuming you are under http folder exactly one level with your root project. You can create folder named contract here and all your files that act as interface you can place here – Faris Rayhan Mar 9 '17 at 9:30

protected by gnat Oct 8 '16 at 9:23

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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