views:

47

answers:

2

I have a factory class I'm making in PHP. Each instance represents a row from a database table.

Since I'll be dealing with dozens of database rows, it would be silly to have each instance do a select on instantiation. So I have a method to just dump values in to the object, for use in conjunction with a database query that returns a lot of rows.

But from time to time, I'll also want to have the object look up all the values in a query. So, I'll have another method that takes the primary key as an argument, and looks up the values from a database query.

So it seems that between these two methods, I won't really need a __construct method.

Is there a name for this type of pattern, more specific than 'factory'? What should I call these two different methods for constructing the object -- are there commonly used names for these methods?

+2  A: 

I think the pattern you have is somewhat similar to the table data gateway.

Since it needs access to the database, I would recommend giving it a constructor. You can pass the constructor the database object (eg. PDO if you use it, or others), so the class does not need to know how to connect to the database.

Otherwise your idea seems good.

Jani Hartikainen
Well, for this class, I don't want an all-purpose table gateway. There's just one select, and only one field will be updated for the purposes of this class. I'm more concerned about the instantiation methods of this object.
One instance per row would be [Row Data Gateway](http://martinfowler.com/eaaCatalog/rowDataGateway.html), but I'll upvote anyway
Gordon
@user151841 row data gateway may be what you want then. @Gordon you're absolutely right, I misread the question a bit :) Although I must say I prefer table data gateway over row data gateway ;)
Jani Hartikainen
A: 

Maybe you need a DAO storage class in addition to your data class?

<?php
class Row {
  private $fields1;
  private $fields2;
  __construct($field1, $field2) {
    $this->fields1 = $fields1;
    $this->fields2 = $fields2;
  }
}

class Storage {
  public load($id) {
    $rawRow; // loaded from db
    return $this->createRow($rawRow);
  }
  protected createRow(array $rawRow) {
    return new Row($rawRow['fields1'], $rawRow['fields2']);
  }
}
?>
seva.lapsha