PHP Object-oriented selection factory and update factory code sample sharing

Source: Internet
Author: User
Tags dsn rewind
PHP Object-oriented selection factory and update factory code sample sharing

Select Factory and update Factory mode, the class for this pattern (Updatefactory and Selectionfactory classes) is used to create SQL statements.

Because there are more things to learn before, here is where you try to put the sample code of the previous correlation pattern together for learning and review.

The following code is code snippets and involves connecting to the database, unable to debug the whole (some parts alone can be taken out), so the understanding.

Update factory abstract class updatefactory{abstract function newupdate (\woo\domain\domainobject $obj); Stitching updated or inserted SQL statements protected function buildstatement ($table, array $fields, array $condition = null) {$terms = array (); The actual value that is represented by the placeholder in the SQL statement if (!is_null ($condition)) {//Conditionally stitching the UPDATE statement, unconditionally stitching the INSERT statement $query = "Update {$table} SE            T "; $query. = Implode ("=?", Array_keys ($fields)).            " = ? ";            $terms = Array_values ($fields);            $cond = Array ();            $query. = "WHERE";                foreach ($condition as $key + $val) {$cond [] = "$key =?";            $terms [] = $val;        } $query. = Implode ("and", $cond);            } else {$query = "INSERT into {$table} (";            $query. = Implode (",", Array_keys ($fields));            $query. = ") VALUES (";                foreach ($fields as $name = + $value) {$terms [] = $value;            $qs [] = "?";       }     $query. = Implode (",", $qs);        $query. = ")";    } return Array ($query, $terms);        }}//generate SQL statements by Domain Model class Venueupdatefactory extends updatefactory{function newupdate (\woo\domain\domainobject $obj) {        $id = $obj->getid ();        $cond = null;        $values [' name '] = $obj->getname ();        if ($id >-1) {$cond ["id"] = $id;    } return $this->buildstatement ("Venue", $values, $cond);        }}//Select Factory Abstract class selectionfactory{abstract function newselection (Identityobject $obj); The WHERE condition statement of the SQL statement is stitched by the Identity object function Buildwhere (Identityobject $obj) {if ($obj->isvoid) {return ARRA        Y ("", Array ());        } $compstrings = Array ();        $values = Array ();            foreach ($obj->getcomps () as $comp) {$compstrings [] = "{$comp [' name ']} {$comp [' operator ']}?";        $values [] = $comp [' value ']; } $where = "where".        Implode ("and", $compstrings); Return ARRay ($where, $values);        }}//Splicing SELECT statement class Venuselectionfactory extends Selectionfactory {function newselection (Identityobject $obj) {        $field = Implode (', ', $obj->getobjectfields ());        $core = "Select $fields from Venue";        List ($where, $values) = $this->buildwhere ($obj); Return Array ($core. "    ". $where, $values);          }}//now to review the knowledge of the previous study//Field object class Field {protected $name = null;         Field name protected $operator = NULL;         Operator protected $comps = Array ();     Array protected $incomplete = False for the storage condition;    Checks if the condition array has value function __construct ($name) {$this->name= $name; }//Add Where Condition function addtest ($operator, $value) {$this->comps[] = Array (' name ' = = $this->name, ' O    Perator ' = $operator, ' value ' and $value);    }//Gets the array function getcomps () {return $this->comps; that holds the condition    } function Isincomplete () {return empty ($this->comps); }}//identity object, the main function is splicing whereConditional Statement class Identityobject {protected $currentfield = null;        The Field object of the current operation protected $fields = Array ();    Field Object Collection Private $and = null;            Private $enforce = Array ();            Qualified legal field function __construct ($field = null, array $enforce = null) {if (!is_null ($enforce)) {        $this->enforce = $enforce;        } if (!is_null ($field)) {$this->field ($field);    }}//Get Qualified legal field function Getobjectfields () {return $this->enforce; }//The main function is to set the Field object that currently needs to be manipulated function field ($fieldname) {if (! $this->isvoid () && $this->currentfiel        D->isincomplete ()) {throw new \exception ("incomplete field");        } $this->enforcefield ($fieldname);        if (Isset ($this->fields[$fieldname]) {$this->currentfield = $this->fields[$fieldname];            } else {$this->currentfield = new Field ($fieldname); $this->fields[$fieldnaMe] = $this->currentfield;                    } return $this;    Use coherent syntax}//field collection is null function isvoid () {return empty ($this->fields); }//Check if the field is legal function Enforcefield ($fieldname) {if (!in_array ($fieldname, $this->enforce) &&!e            Mpty ($this->enforce)) {$forcelist = implode (', ', $this->enforce);        throw new \exception ("{$fieldname} not a legal field {$forcelist}");    }}//Add a Where condition to the Field object function eq ($value) {return $this->operator ("=", $value);    } function lt ($value) {return $this->operator ("<", $value);    } function gt ($value) {return $this->operator (">", $value); }//Add a Where condition to the Field object private function operator ($symbol, $value) {if ($this->isvoid) {throw new        \exception ("No object field defined");        } $this->currentfield->addtest ($symbol, $value);             return $this;                        Use coherent syntax}//Get the Where condition array for all the Field object collections in this class function Getcomps () {$ret = array ();        foreach ($this->fields as $key = + $field) {$ret = Array_merge ($ret, $field->getcomps ());    } return $ret;        }}//Data Mapper class Domainobjectassembler {protected static $PDO; Persistencefactory is not implemented in this example, according to the original book that the reader himself//Its main function is to generate the appropriate type of select Factory class, Update factory class or Collection object// This class is the function __construct (persistencefactory $factory) that maps the database table and the domain model at initialization time, depending on the Persistencefactory object that is passed in {$this-        >factory = $factory;            if (!isset (self:: $PDO)) {$dsn = \woo\base\applicationregistry::getdsn ();            if (Is_null ($DSN)) {throw new \woo\base\appexception ("NO DSN");            } self:: $PDO = new \pdo ($DSN);        Self:: $PDO->setattribute (\pdo::attr_errmode,\pdo::errmode_exception); }}//Gets the preprocessing object, using the SQL statement itself as the object array key function Getstatement ($STR) {if (!isset ($this->statements[$str]) {$this->statements[$str] = self:: $PDO->prepare ($STR);    } return $this->statements[$str];        }//Returns a data function FindOne (Identityobject $idobj) {$collection = $this->find ($idobj) according to the Where condition;    return $collection->next (); }//Returns a data Set function find (Identityobject $idobj) {$selfact = $this->factory->getselection According to the Where condition             Factory ();    Get Select Factory Object list ($selection, $values) = $selfact->newselection ($idobj);                    Gets the SQL statement $stmt = $this->getstatement ($selection);                            Gets the Preprocessing object $stmt->execute ($values);        $raw = $stmt->fetchall ();                    return $this->factory->getcollection ($raw); Remember collection object, the following glue code review}//According to the WHERE condition insert or update a data function insert (\woo\domain\domainobject $obj) {$        Upfact = $this->factory->getupdatefactory (); Get Update Factory Object list ($update, $values) = $upfact->newupdate ($obj);                Gets the SQL statement $stmt = $this->getstatement ($update);        Gets the Preprocessing object $stmt->execute ($values);        if ($obj->getid () <0) {$obj->setid (self:: $PDO->lastinsertid);    } $obj->markclean (); }        }

Here is a review of the collection class, of course, this class and the collection class used above is different, because at least the mapper class here has changed a bit compared with the previous

Iterator interface-defined methods:

Rewind ()            points to the beginning of the list (    )            returns the element at the current pointer key ()                returns the current key (for example, the pointer's finger) next ()                valid ()

The following class deals with multiple rows of records, passes the raw data and mapper taken out of the database, and then creates it as an object when the data is fetched by the data mapper

Abstract class Collection implements \iterator{protected $mapper;        Data Mapper protected $total = 0;    The total number of collection elements protected $raw = array ();    Original data private $result;        Private $pointer = 0;    Pointer private $objects = array (); Object collection function __construct (array $raw = Null,mapper $mapper = null) {if (!is_null ($raw) &&!is_null ($            Mapper) {$this->raw = $raw;        $this->total = count ($raw);    } $this->mapper = $mapper;        } function Add (\woo\domain\dmainobject $object) {//Here is a direct add object $class = $this->targetclass (); if (! (        $object instanceof $class) {throw new Exception ("This is a {$class} collection");        } $this->notifyaccess ();        $this->objects[$this->total] = $object;    $this->total + +;    } abstract function Targetclass ();      protected function notifyaccess () that is implemented in subclasses to check the type when inserting an object () {//Don't know what to do}  Private Function GetRow ($num) {//Gets a single piece of data in the collection, which is where the data is created as an object $this->notifyaccess () through the data mapper;        if ($num >= $this->total | | $num < 0) {return null;        } if (Isset ($this->objects[$num]) {return $this->objects[$num]; } if (Isset ($this->raw[$num]) {$this->objects[$num] = $this->mapper->createobject ($this->r            aw[$num]);        return $this->objects[$num];    }} Public Function rewind () {//reset pointer $this->pointer = 0;    The public function is current () {//Gets the present pointer object return $this->getrow ($this->pointer);    } Public Function key () {//Get current pointer return $this->pointer;        The public function next () {//Gets the current pointer object and moves the pointer down $row = $this->getrow ($this->pointer);    if ($row) {$this->pointer + +} return $row; } public Function valid () {//Verify return (!is_null ($this->current ()));        }}//Subclass Class Venuecolletion extends Collection implements \woo\domain\venuecollection{function Targetclass () {    return "\woo\domain\venue"; }}//client//Initializes a super factory class that can obtain a venue type of Select Factory class, Update factory class, or Collection Object $factory = \woo\mapper\persistencefactory::getfactory ("    Woo\\domain\\venue ");        $finder = new \woo\mapper\domainobjectassembler ($factory);    Data Mapper $idobj = $factory->getidentityobject ()->field (' name ')->eq (' The Eyeball Inn ');                    Set the WHERE condition statement $collection = $finder->find ($idobj); Finds a data collection (a collection object) based on the Where condition foreach ($collection as $venue) {print $venue->getname ()."    \ n "; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.