6

When I build a RESTful API, I use an MVC pattern. And in order to make controllers skinny and code reusable outside of the API (e.g. in Cron tasks), I put much of my code into services (commonly known as libraries).

My routers delegate to controllers which then delegate to services, which use models.

I am wondering: Does it make sense for services to use models? So

router > controller > services > models

Or, should models use services? So

router > controller > models > services
Chad Johnson
  • 491
  • 4
  • 13

2 Answers2

5

In the MVC pattern, eberything that is not part of the Controller or View is considered to be part of the Model side of the triad. This means that from an MVC perspective, your question is moot, because both your services and models are part of the MVC Model side of the triad.

As most MVC frameworks provide data access services as part of their Model component, which you may want to use as well when accessing your code from outside the API, it makes most sense to place your services layer between the controller and models.

Bart van Ingen Schenau
  • 71,712
  • 20
  • 110
  • 179
1

It helps to make a distinction between:

  • Helpers - support code that is not aware of your model, e.g. date formatting.
  • Services - support code that is aware of your model, e.g. bills credit card, updates user record, sends user email

I'm not quite sure which of these you mean by "library". Anyway, following your terminology, I suggest this chain:

router > controller > services > models

The service layer is optional: for simple operations the controller can call the model directly. And anything can call a helper.

To refine your terminology a bit more, you can modularise the model.

paj28
  • 1,663
  • 1
  • 13
  • 13