Allocation of responsibilities in the MVC

Asked

Viewed 155 times

0

I’m starting work with MVC, more specifically with Laravel and Eloquent (the ORM embedded in Laravel).

I have studied and continue to study the MVC standard and its advantages. However, in practice, I was left with some doubts as to where to place the appropriate responsibilities. Mainly for the flexibility of the framework and the several dozen variations of MVC.

Come on: in my application I will use methods that will bring for example news highlighted. Should such method be in the Model or in my Controller? Why?

  • 5

    On the model, think of it as a bridge between you and the comic.

1 answer

3

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

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

Returning to your question, you say you want to search for news in the spotlight. I would do it this way:

  1. Have a method in the controller mapped to the route (for example) /noticias/destaques. The method could be called NoticiasController::destaquesAction.
  2. Have an entity Noticia, that represents the news in your database, and a class NoticiasRepository, responsible for bringing news or a collection of them.
  3. Have a method NoticiasRepository::getNoticiasEmDestaque that returns a collection of featured news, ordered to your liking.
  4. Finally, call this method from your controller and render it in the view.

This is how I usually develop my applications. If you have any opinion about it, just say the word. :)

  • I know the publication is a little old, but it would be correct to call it Noticiasdao instead of Noticiasrepository?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.