Search code examples
phpmodel-view-controllerbackend

Does a Model communicating with another Model Break the MVC design pattern?


Learning the MVC model has been a bit of a journey. However, I find myself tripping up over small things every now and again such as if a controller can have a one to one relationship with a model or many controllers to one model, etc. Is there a universal pattern to which is the best abstraction or is it up to the needs and complexity of a program. If so, is it considered good practice to have a model validation validating data that enters in to user model.


Solution

  • There is no standardized way to treat the level of abstraction, only best practices. Furthermore, best practices may vary depending on the framework or flavor of MVC.

    You can consider the following patterns:

    1. The User model contains the required validation logic, e.g. to ensure the userid field is never null and an initialized user object.

    2. Alternatively, you can have a generic Validation model, e.g. making sure the data contain only allowed characters etc. The User model inherits the Validation model and adds user-specific data fields to it

    The decisions on abstraction should be based on the need to couple/decouple and reuse various parts of the code.

    In Pattern 1, the validation logic is always kept together with data. You will never need to run the validation logic without the user data.

    Pattern 2 keeps the validation logic isolated, thus it can be reused for any model.

    Likely, there are many other patterns but discussing them in abstract terms is a bit difficult.