开发者

A self-creator: What pattern is this? php

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;
       开发者_JAVA百科     $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().


I think it's the Factory method pattern.

The factory method pattern is an object-oriented design pattern to implement the concept of factories.

Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.

Outside the scope of design patterns, the term factory method can also refer to a method of a factory whose main purpose is creation of objects.


As this is related to databases, I think this is close to something that may be called Data Mapper.

If you are looking for something like this in PHP, move to Propel ORM. Look at the first example : it's almost your code !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜