I am working on a simple JSON API application, and I am confused with my application architecture.
The pattern is MVC with repositories. Models are simple classes that encapsulate business logic of a single entity (resource). They are not concerned about how and where they are stored, or how they are displayed.
Controllers are only concerned about what to do when a certain action (user request) happens. For example, when certain API is hit with certain parameters, what do we need to do.
Repositories provide an interface for storing, retrieving, and doing other operations on resources (models). They are the only place where communication with the data layer happens.
Data layer is implemented using plain SQL (actually I'm using an SQL builder, but I think that doesn't make a huge difference). I am using repository pattern that operates with models. For example, it has a method add() that accepts a model instance as a parameter, and find() method that is used to retrieve models. In my implementation both add() and find() methods would translate model attributes to database columns, and perform INSERT/SELECT queries.
Here are some examples. Suppose we're creating some resource (e.g. POST to /api/resources/): - Controller logic: make a new instance of Resource model, populate it with attributes coming in request. If model is valid, call ResourceRepository's add() method by passing model as the parameter. - Repository logic: read model's attributes, and insert them into corresponding DB tables. Then update caches if necessary, and so on.
Another example with retrieving a resource (e.g. GET /api/resources/): - Controller logic: call ResourceRepository's find() method, pass paging/sorting/filtering parameters as necessary. - Repository logic: construct SQL queries, retrieve data from tables, create a model instance, populate it with attributes, and return to the controller.
I am now stuck with repository implementation. I have a lot of code that translates DB columns to model attributes (and vise versa). And it looks like a huge dictionary with column mapping, which just doesn't seem right...
Actually I have one idea in mind, but I'm not sure should I go this way or not. What about implementing attribute mapping as a variety of View? Because the way I see the View is: it gets data as an input, and renders it into something that is presented to the client. Why can't the input be, for example, raw data from DB and the client be the model? Is that a terrible idea? Or how would you implement this?
Thank you for any suggestions.
Aucun commentaire:
Enregistrer un commentaire