2010年7月17日星期六

Re: [fw-db] Extending Zend_Db_Table_Row_Abstract

On Jul 17, 2010, at 12:34 PM, Brad Waite wrote:

> On 7/17/2010 10:56 AM, Bill Karwin wrote:
>
>> I'd extend the Row class only to add operations on a row of data.
>
> Okay, that makes sense. Given the need for a Data Mapper whose
> parts are very similar to the Row class, wouldn't this make a good
> base class?

Not all patterns are good for making base implementations. Many
pattern need to be tailored to a specific case. Trying to make a one-
size-fits-all base class that anyone can use make that base class so
complex that it's both slow and hard to use. Data Mapper might be in
this category. The mapping logic you need is very situation-specific.

In your example, you aren't actually doing any mapping, you're just
creating a way to add other properties besides those that map directly
to database columns. Your class doesn't provide any hooks for mapping
the database columns, except for a 1-to-1 verbatim mapping, which is
sort of a degenerate case and has very little value.

I'd expect a Data Mapper base class at least to use optional mutators
(getters/setters) that are backed by the Table Row properties.

abstract class DataMapper
{
protected $tableRow = null;
protected $_name = null;

public function __get($name){
$method = "_get_".$name;
if (method_exists($this, $method)) {
return $this->$method();
} else {
return $this->tableRow->$name;
}
}

public function __set($name, $value){
$method = "_set_".$name;
if ($name != 'tableRow' && method_exists($this, $method)) {
$this->$method($value);
} else {
$this->tableRow->$name = $value;
}
}
. . .
}

Now I have a hook so I can define a method like _set_priority() for
the 'priority' property, whether priority is one of the database
columns or whether it only lives in the Mapper. In that method, I can
write code to do something with that field. Maybe priority should get
transformed into an object instead of just being a scalar we fetched
from the database.

This gives us more flexibility, but there's still use cases for Data
Mapper that this doesn't handle. It's still more or less coupled to
the physical design of the underlying table.

>> I've written a class that fetches hierarchical data from a db table
>
> How are the relationships defined?

Too much to go into right here, but I'll just say I wrote this code as
part of an experiment to implement the Closure Table design for
hierarchical data. See my presentation "Hierarchical Models in SQL
and PHP" for information: http://www.slideshare.net/billkarwin/models-for-hierarchical-data

Also take a look at the accompanying TreeTable class: http://framework.zend.com/svn/framework/extras/incubator/library/ZendX/Db/Table/TreeTable.php

Regards,
Bill Karwin

没有评论: