A self-creator: What pattern is this? php
- by user151841
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 example :
class fruit {
public $id;
public function __construct( $id ) {
$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 = $val WHERE id = $this->id";
}
public static function create( $id ) {
$sql = "INSERT INTO Fruits ( fruit_name ) VALUE ( '$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().