A self-creator: What pattern is this? php

Posted by user151841 on Stack Overflow See other posts from Stack Overflow or by user151841
Published on 2010-05-10T15:28:23Z Indexed on 2010/05/10 16:24 UTC
Read the original article Hit count: 109

Filed under:
|
|

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().

© Stack Overflow or respective owner

Related posts about oop

Related posts about design-patterns