Allocation of responsibilities in MVC

0

I'm starting work with MVC, more specifically with Laravel and Eloquent (the ORM built into Laravel).

I studied and continued studying the MVC standard and its advantages. However, in practice, I was left with some doubts about where to allocate due responsibilities. Mainly because of the flexibility of the framework and the several tens of variations of the MVC.

Let's go: in my application I will use methods that will bring prominent news, for example. Should such a method be in the Model or in my Controller? Why?

    
asked by anonymous 29.09.2014 / 22:46

1 answer

3

Think of controllers as just one of the entry points for your application, so you should have as little code as possible. I say this because there may be other entry points, such as commands, APIs, etc.

In general, most of the code in my applications resides in models (which for me are representations of the application entities, which in turn are replicated in the database); in repositories (responsible for bringing an instance or collection of entities); and services (which are responsible for performing a specific task in the application).

Returning to your question, you say that you want to search for news stories. I would do it like this:

  • Have a method in the driver mapped to the route (for example) /noticias/destaques . The method could be called NoticiasController::destaquesAction .
  • Have a Noticia entity, which represents the news in your database, and a NoticiasRepository class, responsible for bringing news or a collection of news.
  • Have a NoticiasRepository::getNoticiasEmDestaque method that returns a collection of featured news, sorted to your liking.
  • Lastly, call this method from your controller and render it in the view.
  • That's the way I usually develop my applications. If you have any opinion, just let me know. :)

        
    01.10.2014 / 14:07