php – MVC Call model from another entity

Question:

I am working with CodeIgniter and as you know PHP is quite free and allows us to do many things, sometimes bad practices.

The question is more theoretical than the Framework. In an MVC architecture, is it bad practice to call the model from another entity? Ex:

    Controller:
    - Garantia
    - Novedad
   Modelo
    - Model_Garantia
    - Model_Novedad

In other words, would calling the Novelty model from the Warranty Controller comply with the SOLID, OOP and MVC principles? Or should I create an object of type Novelty and through that find what I need from the Model_New?

Answer:

When implementing a RESTful web service with an MVC architecture with something basic like a CRUD, it is necessary to know that the specification indicates that the entity/model for which it was designed must be called in each of the controllers.

Based on the SOLID Principles, the first is the Single Responsibility Principle, which establishes:

Each module or class must have responsibility for only one part of the functionality provided by the software, and this responsibility must be entirely encapsulated by the class.

We can realize that by making classes dependent you would be generating low cohesion and high coupling. Therefore, making a modification to one would directly affect the other class.

The main problem with this RESTful approach is that if you have two Models, one called Post and the other Comment , what the specification indicates to be able to call a Post with all the associated Comment's would be as follows:

GET /post/1
{
  "title": "My Post",
  "author": { 
    "firstName": "Angel",
    "lastName": "Oropeza"
  },
  "comments": [1, 2, 3, 4]
  // ... more fields here
}

GET /comment/1
{
  // ... more fields here
}
...
GET /comment/4
{
  // ... more fields here
}

That is, a call must be made to obtain the Post with id 1 and then make a call to each of the comments associated with this Post.

Finally to mention that some pages have migrated their REST services to GraphQL like GitHub. You can get more information about it here .

Scroll to Top
AllEscort