I am currently trying to figure out how to properly implement the the MVC principle. Lets take for example a simple blog. I have a database that contains two tables: Blogs and comments. The blogs table consists of fields like a title, content, date, etc. Comments contain an autorname, a date, content, stuff like that.
Lets start with the easier items. I have a couple of views. Like:
- Write / edit blog item
- Display a blog item
- Display a summary page (e.g. recent blogs, popular topics, etc)
- etc
The controllers are also quite clear to me:
- Admin controller (transfers blog items to the write / edit views or sends them back)
- Blog controller (transfers blog items to the blog views, like the summary page or the page where just one is displayed. This also retrieves the comments)
- Comment controller (transfers data from the comment creation / deletion views)
But then comes the models. I really don’t know how I should implement these. The Zend Framework quickstart page recommends a pretty small model with only private properties and getters and setters for the specific item. They recommend doing the database logic in a Mapper.
But here’s my question. Let’s say I want to fetch the most recent blog items. How would you implement this? Where would you write the function fetchRecentItems()? In the mapper? It seems that this should contain only basic CRUD statements. In another model, like BlogService? In the controller?
Can someone help me out here? I would love to see a quick pseudo-code example.
(I tried to summarize my knowledge to make my thinking process a little bit more clear. If I understood something wrong, please correct me. Thanks!)
It depends how far you want to go with it really. Personally I would use a Service class, interacting with mapper classes, called from the controller. So your class might look something like:
so then in your controller:
this starts to look like a lot of code to do a simple thing, but when you start seeing common elements between the classes you can refactor a bit to improve things. E.g. if you have multiple service classes that look like this you can move the get/set mapper functions into a base service class that they extend. You could add some logic to the getMapper() function that would work out what the correct mapper is based on the class name if one hasn’t been supplied, saving you having to pass it in each time.
There isn’t a ‘right’ answer here though, these patterns exist as solutions to common programming problems. Use as many or as few of them as you feel is appropriate for your app.