|
Posted by Dikkie Dik on 02/22/07 17:24
<snip>
> One thing which confuses me is how to use databases in the OO approach.
> Imagine we have a system which deals with music CDs:
>
> class MusicCD {
> private $title;
> private $artist;
> function __constructor($title, $artist) {
> $this->title = $title;
> $this->artist = $artist;
> function displayCD() {
> echo $this->title.' '.$this->artist;
> }
> }
Nothing wrong with that. For storing it in a database, you may add an
"ID" property. Also note that this object is immutable: it cannot be
changed after construction. This could be exactly what you need if you
only want to show CDs from a database table, but if you want to edit the
fields, you'd have to add getters and setters to the class.
> Now, we want to save this information in to a database, what is the
> correct way (best practice) for doing this; is it to create a saveCD
> method in my musicCD class? Should this method expect a database object
> to be passed in, or, should it call static methods of another class?
I usually work with "record" classes (like your MusicCD class) and with
collection classes that represent tables rather than records. My first
step to database code is to put the database handling stuff in the
collection classes. These can be lazy (see
http://www.w-p.dds.nl/article/wrtabrec.htm#laziness ). Your collection
class can now feature a Store(MusicCd $CD) method that checks the
properties of the record. If its ID is an integer, it builds up an
UPDATE query. If it is NULL, it is a new record, so an INSERT query has
to be built and the ID property has to be set to the generated ID after
storing.
Next step is to note which database code is the same or similar in all
these classes and extract that to either a superclass or a helper class,
or both.
<snip>
> Surely in the OO concept the MusicCD class doesn't need to know about my
> table structure etc, would this be a case for a MusicCDDatabase class
> which knows about MusicCD and DB?
You are getting the hang of it. Database handling is not the
reponsibility of a record. It may be the responsibility of a collection,
and the collection may delegate this responsibility to a more
specialized class.
Best regards.
Navigation:
[Reply to this message]
|