I have several classes that are basically interfaces to database rows. Since the class assumes that a row already exists ( __construct
expects a field value ), there is a public static function that allows creation of the row and returns an instance of the class.
Here's a pseudo-code ( so there are mistakes and missing improvements in this ) example :
class fruit {
public $id;
public function __construct( $id ) {
if ( ! is_numeric($id) ) {
throw new Exception("Id is not numeric.");
}
$this->id = $id;
$sql = "SELECT * FROM Fruits WHERE id = $id";
...
$this->arrFieldValues[$field] = $row[$value];
}
public function __get( $var ) {
return $this->arrFieldValues[$var];
}
public function __set( $var, $val ) {
$sql = "UPDATE fruits SET $var = " . mysql_real_escape_string($val) . " WHERE id = $this->id";
}
public static function create( $fruit ) {
$sql = "INSERT INTO Fruits ( fruit_name ) VALUE ( '" mysql_real_escape_string($fruit) . "' )";
$id = mysql_insert_id();
$fruit = & new fruit($id);
return $fruit;
}
}
$obj1 = fruit::create( "apple" );
$obj2 = & new fruit( 12 );
What is this pattern called?
Edit: I changed the example to one that has more database-interface functionality. For most of the time, this kind of class would be instantiated normally, through __construct()
. But sometimes when you need to create a new row first, you would call create()
.