2008年7月22日星期二

Re: [fw-mvc] Best practices in a thin-controller application

On Tue, Jul 22, 2008 at 3:26 PM, David Mintz <david@davidmintz.org> wrote:
> Which brings me to another question, maybe sort of OT. If your model's
> constructor requires an id parameter, how do you instantiate a "blank"
> object to be populated with data provided by the user and then -- excuse me
> for thinking database -- inserted into a table? I am thinking of RDMSes that
> have auto-incrementing.You find out the id after the insert.

Good question. In my actual code (as opposed to the examples posted
here) the constructor allows a null ID for the reasons you've
described.

Actually my real constructor allows a wide variety of "ID" parameters,
some of which might be considered cheating :) For example, this is
allowed:

[code]
$table = new Travel_Table_Trips();
$row = $table->find(15)->current();
$tripModel = new Travel_Trip($row); // ...something smells funny...
[/code]

I allow this for convenience and performance reasons, since there are
occasionally cases where the code instantiating the Trip object has
already, for one reason or another, pulled that Trip object's
associated row from the underlying database table. The problem, of
course, is that neither Travel_Trip nor Travel_Agent is supposed to
expose its database dependence to the outside world...all of the
persistence stuff should happen inside the "black box."

For instance, I have a Travel_Agent class whose job it is to find and
return lists of Trips. Internally, it does this by referencing the
same database table that internally backs the Travel_Trip module:

[code]
class Travel_Agent
{
public function findTripsByCountry($country)
{
$table = new Travel_Table_Trips();
$select = $table->select();
$select->where('country = ?', $country);
$rowset = $table->fetchAll($select);
$list = new Travel_TripList();
foreach ($rowset as $row) {
$list->add(new Travel_Trip($row));
}
}
}
[/code]

See why it's helpful to be able to construct the Travel_Trip object
from the row? It saves Travel_Trip from having to reload an
already-loaded row from the database. It does so, however, at the
expense of Travel_Agent being aware of the fact that Travel_Trip is
backed by a database table.

Comments? Is there a way to keep from having to reload the row
without exposing Travel_Trip's database dependency?

Thanks!
Adam

没有评论: