Where to put SQL queries that join on multiple tables? - php

I am using an MVC framework and have a photo SQL table and an album SQL table. Queries for the photo table go in the photoTableModel class, and queries for album table go in the albumTableModel class.
Where do I put queries that use both tables?
For example, the following query uses both tables. Do I place the query in the photoTableModel, albumTableModel, a new table model altogether, or maybe even a service?
SELECT `photo`.`id`
, `photo`.`name`
FROM `photo`
JOIN `album`
ON `album`.`album_id` = `photo`.`album_id`
AND `album`.`album_id` = 1
;

The center of the architecture is models, not tables. Semantically, which model is being described or operated on here?
This appears to be retrieving a list of photos, with some album information included in the elements of that list. So I suspect that this is related to the Photo logical model. So wherever you put this in your architecture and framework, it should be semantically related to that model.
How your framework defines things is up to that framework, so I really can't be more specific. Different frameworks do different things in different ways. In general, however, in the MVC pattern you want to build your logic and architecture around the models. And what you get from this query is a list of photos (with some extra information), so it's related to the Photo model.
Models can be direct one-to-one representations of tables. But they don't need to be. It looks like you're artificially limiting your models to be exactly that, which has led to this issue. Maybe you extend the Photo model concept to include album information? Maybe you create a DTO that's a hybrid of the two? Maybe you add an Album property to your Photo model? There are many ways to go about organizing models. The point is to keep the semantics of those models clear. Models represent domain concepts (like Photo), not database tables (like photoTableModel). The database tables simply persist the model information to be re-constructed later. As such, the database is an edge concern for the domain, not a central one.

Related

MVC - should a model interact with (an)other model(s)? Or the controller should do that?

Apologise if it sounds a dumb question, but if I never ask, I'll never learn. I have been recently working with the MVC implementing pattern, and I'm still learning stuff, so please be patient with me.
I've been recently working on a multi-languages website that uses a custom MVC framework for a client. In some places I'd need to display some information from more than one table, like an article (from the articles table), the name of the languages that this article is written in (from the languages table), the languages that this article is not yet written in (from the languages table also), and the author (from the authors table).
I have a model for the articles, a model for the languages, and a model for the authors, and each has its own controller.
If I only query articles tables only or the authors tables only, there is no issue, but the confusion comes when I want to display information from this different tables into a single view.
How I should do that?
Instantiate a language model object and an author model object in the article controller and call their related functions to get the data and then combine/merge their data with the data from the article model (all in the article controller as mentioned)?
Instantiate the language model and the author model in the article model and call their functions to get their data, then combine/merge the their data with the data from the article model itself?
Do a join or nested select in the article model to get the data from multiple tables, and not interact with any other model, even if that mean some queries will be repeated in more than on model?
Another approach?
What is the best way do that?
This can be done in several ways:
- Create a view (a virtual table of MySQL) which using join, nested select or whatever you want to achieve all necessary information and create a model on top of this view in MVC (this model can only retrieve info from the view not alter it, however)
- Use repository pattern. A repository wrap many models and you can implement business logic (which might be CRUD on multiple models/tables) here. The controller simply use the repository instead of model.
In summary the model, repository should wrapping all the business logic of its own never let the controller do these stuff.
Regards,

Should I create different SQL tables for similar usages or create just one with a parameter?

In my application (symfony2 / doctrine 2 / mysql), I have a forum and a blog and a small social network.
All require the ability to post some content.
Should I better create different tables for the specific elements (a blog_post, a forum_post, a social_post tables) or create just one post table and attach it to a post_category table which would contain those forum/blog/social_network rows ?
The idea is the usages and specifications for those application parts might become a bit different at a later point in time and though it might be easier to have one single table for the moment, separating them might be easier to maintain in the long run.
What is a best practice in that case ?
You might use Table inheritance for this.
Having abstract Post entity as parent to BlogPost, ForumPost and SocialPost. This way you'd have standalone entities with DRY properties.

Why do I need a Application_Model_User and Application_Model_DbTable_User in Zend?

Is there any point in having both? I followed a Zend tutorial which told me to create a user model but can't I just model the user in the DB model class?
Thanks
It's part and parcel of the concept of "separation of concerns" http://en.wikipedia.org/wiki/Separation_of_concerns
Your model class takes care of business logic, validation, variable manipulation etc and your db model class should just handle dealing with the database, that way if you need to replace the db model it wont affect the main model as much, and if you replace the main model it wont affect the db model as long as the right parameters are passed into it.
Yes, you can model your user in Application_Model_DbTable_User (DbTable class) and it will work fine as long as all of the data you need is in that one table.
At some point you will likely start working with objects that should be represented in more then one table. This is when you will discover the need for a different way to do things.
A better simple example of where a mapper and domain object might matter:
The mp3 file.
At it simplest a single music file should probably be represented by at least 3 db tables:
album: a table representing the album the song comes from
artist: the artist that recorded the song
track: the information about the track itself
each artist can have multiple albums, each album will have one artist and will have multiple tracks, each track will belong to one album and one artist (different versions will be different tracks).
As you can see the database stucture of even a simple mp3 collection can become very complex very quickly. In most cases even a simple user record will spread across multiple tables depending upon how much and what kind of data is being persisted.
For some help in understanding how and why to implement mappers and models I found these resources very helpful.
Building a Domain Model, covers what a domain model is and how to build one in PHP.
Adding Mappers to a Domain Model, adds mapper function to the same domain model.
Survive the Deepend, A Zend Framework starter that focuses on models and testing.
The first two links are done in plain PHP but are still very helpful.

own ORM: database records in case of JOIN?

We are doing our own framework with ORM capability. The database tables are classes now, but how about records? Lets imagine two tables:
Users
ID,USERNAME
Emails
USER_ID,ADDRESS
so, a record object will have getID(), getUSERNAME() methods, etc but if the two tables are JOIN-ed, it cant have two types right? Since there is no multiple inheritance. And what about field collision?
DBIx::Class handles this by having a Class for each table, and joins are represented by a method that gets an object matching the other table..
$myAddress = $myUser->emails->address;
I think every class should represent a record and a whole table should be an array (or some other collection) of objects. Take a look at http://www.doctrine-project.org/ to get some ideas.
And for JOIN, you should have some mechanism for defining aliases. That way, you can deal with field collision.
And for getters and setters, you can use __call, __get and __set. See http://php.net/manual/en/language.oop5.overloading.php for more info.
I'm providing some insight based on the Model/ORM implementation of this PHP UI Framework . Here are some suggestions from me:
Don't decide blindly to map functions into fields. Why not use get('field') and set('field'). There is no downside (apart from lack of IDEs hinting), but you can avoid code generation or catch-all which usually is slower.
When joining you wouldn't necessarily want multiple objects. In my ORM a single Model can work with joined tables. This introduces transparency and when you call $model->set('address') it might be associated with joined table. Im still using sub-instance of a dynamic query for sub-selects but for joins there is no need.
I've see a lot of power of inheritance and ability to re-shape parent models in parent model. Each table can have multiple models depending on your business uses.
Models and ORM should be separated but should play together very closely. I've also managed to make everything play well with generic views and generic controllers, which is a great time-saver.
Hopefully this would help find your own way or to decide on not implementing your own ORM. It's not an easy task.

question about the mvc pattern

i dont quite understand this pattern.
from what i have read, it looks like one model = one table (if you are using database to store data).
so if i've got a table called tags, i should have a tags model. and with a threads table i create a threads model.
then i got a tags controller and a threads controller right?
so what if i've got a tags_threads_map table for a many-to-many relationship.
should i have a tags_threads_map model eg. in which i get all threads containing a tag? should i have a tags_threads_map controller too?
would be great if someone could explain or give me a good breif tutorial on this.
the most tutorials just give a simple 1:1:1 example.
To fully understand MVC or any software design pattern, you really need to have a go at implementing it and see what your results are.
That said, MVC does not prescribe that one model = one table. In fact, a model could be backed by a number of tables, or even data originating in something other than a relational database (e.g. a web service, flat files, a key-value store or a graph database for example).
I would suggest that creating models and views that represent meaningful aggregates of related tables is probably a good approach. For example, to use the timeworn example of an Order and OrderLine table, an Order model might encapsulate operations on data that will ultiamtely end up in either the Order table or the OrderLine table.
Adhering to strict 1-to-1 mapping of table to Model, View and Controller will only result in an explosion of classes, some of which may not be doing much individually. Better to build Models and Controllers that are more focused on achieving some task identified by the business requirements, rather than just being a projection of the data model.
So the idea is less "one model = one table" and more that you don't want code that manages the data to be interleaved with code that manages the operations on data or code that handles user interaction. If you have some sort of persistance layer that handles mapping of objects to a database, that's enough to have a rudimentary model. If you have some separate code on top of that that does something algorithmic with that data, that's a controller. If you have a way of rendering the data for user consumption, that's a view.
Best example that comes to mind is a spreadsheet: the data in the spreadsheet is your model. If you have expressions in your sheet that manipulate the data, that can be seen as a controller. If you see the data in tabular form, or in a graph, those are two views. The views don't muck with the data or how it's calculated - they format it for your eyes. The controller doesn't format the data for your eyes - it creates / changes / calculates the data. The important part is separating out the concepts so you can, for example, write algorithms that don't care how data is stored, and views that don't care how data is calculated.
In my opinion, it's better to think of a model as a model of an object type, not of one specific table.
Generally, your MVC framework would handle your many-to-many relationships by definitions from within the models for tags and threads.
And you definitely don't need a controller for every model; controllers are generally more closely related to views (though there are usually multiple views to one controller).
This seems like it's too general of a question to be able to be answered to your satisfaction here.
A model can be more dynamic than that. For example, if you have a blog, and a blog has tags, your model might be called Blog and it can have a collection of Tags.
A model can be anything that stores the data. In the web app I'm working on there are several tables for contacts, their addresses which groups they belong to and so on. It's probably best to split them up by types, I should have made a group model but you don't strictly have to do this.
MVC relates to 3d games quite well, MVC is not only for information systems. Consider this:
In 3d graphics the model is map, the polygons and their positions and colours. The view is the camera from which the scene is viewed, a position, zoom and direction. The controller interprets the keyboard and mouse and manipulates both the camera(view) and scene(model).
If this were a shooter game then if:
A user pushes the forward button, the controller moves the camera forward.
A user pushes the throw grenade button, controller adds a grenade to the scene.
The view is presentation, the model is storage/structure and the controller is an in between which tells the view what to display and how to display it based on the state of the system.
Generally you put all the formatting in a view, data in models and logic into controllers.

Categories