views, it means I am not the far out crazy one! ;-)
One of the lessons that someone or somebook taught me when I first
started doing OO development went something along the lines of:- "An
object contains the data AND the methods to manipulate that data".
For some reason this stuck firm and fast with me and was reinforced
when I learned about MVC and the concept that the Models would
represent my real world business items.
I sometimes find myself comparing my classes to other real world items
- like my stapler. It cannot put itself into my desk draw, nor can I
just tell it to go into the desk draw ($model->save()). I actually
have to pick it up, open the draw put the stapler in and close the
draw. This may seem like an odd analogy, but to me it is natural that
most models have no business messing around with the database.
When I think back and try and figure out how I have come about to have
this clear separation between a "model" and a "database access layer"
is because I wrote my first programs before I even knew what a
database was! One example I can think of was that when I had my amiga
many moons ago, I used to love playing yahtzee (with real dice, not on
the computer) but I decided that I would make a computer version of
the game. Now this was nothing clever, just a simple amiga dos based
program that kept track of the game scores in memory - it wasn't even
OO. But because the game only ever existed in memory there was no
"data access" of any kind, but that didn't change how I modelled the
game rules in the program.
Another factor might be the fact that these little programs had
nothing to do with the web, which actually blurs the lines between MVC
components. For example, in my Yahtzee game, it would ask you to
"lock" upto 4 dice and roll again. You could think of this part of the
program as the VIEW. My program would ignore you if you pressed any
key other than 1,2,3,4,5 or Enter. So I would only call my lockDice()
procedure if you pressed one of those keys.
If you map this directly over to web based MVC, your VIEW script might
have similar JavaScript to make sure you only entered a number between
1 and 5. However, your controller would also need to do the same
validation - because we all know that we cannot trust anything from
the user in web based applications.
Perhaps it would be a good exercise to every now and again to just
write a really simple application without any database. Just use
$_SESSION[] or something similar to persist the objects, and then once
you have got the little app running with all the "business logic",
then just tag on a database at the end to save the object state.
I may even sit down and recreate my yahtzee game using ZF just as an
exercise.
Paul
(aka. Gargoyle)
没有评论:
发表评论