Mvc – the relationship between the business logic layer and the data access layer

business-logicdesignmvc

I'm working on an MVC-ish app (I'm not very experienced with MVC, hence the "-ish").

My model and data access layer are hard to test because they're very tightly coupled, so I'm trying to uncouple them.

What is the nature of the relationship between them? Should just the model know about the DAL? Should just the DAL know about the model? Or should both the model and the DAL be listeners of the other?


In my specific case, it's:

  • a web application
  • the model is client-side (javascript)
  • the data is accessed from the back-end using Ajax
  • persistence/back-end is currently PHP/MySQL, but may have to switch to Python/GoogleDataStore on the GAE

Best Answer

The data access layer needs to be aware of the data, which is why it depends on the models. To improve maintainability, the Data-Access-Object (DAO) should solely take care of (de-)serialization. This way you can exchange the way you store data.

For instance, when your application makes use of a component which acts as a data access layer, the component's implementation can be changed to make use of different database types or providers.

How DAOs are implemented strongly depends on your approach to object relational mapping (ORM - assuming you are using an OO programming language). Martin Fowler describes a few common approaches to ORM in his book Patterns of Enterprise Application Architecture. Commonly, you will find some implementation of

Regarding the model, it shouldn't depend on the data access layer (although you will see that models are often littered with metadata for data storage).

Or should both the model and the DAL be listeners of the other?

Depending on your use case, it might be a good idea for your ORM to subscribe to model changes and synchronizes them with the database. Java Persistence 2.0 describes a similar pattern for data synchronization for attached entities (where attached means something like: synchronize the object's state with the database for the duration of the transaction).

In my specific case, it's an Ajax application. Currently I'm using PHP/MySQL for the backend but may have to switch to Python/GoogleDataStore on the GAE.

Various libraries are available for ORM for either technologies. You can check out the Wikipedia ORM comparison page to get a small overview. For GAE, there is Google's documentation.