PHP Object-oriented sample code sharing on domain model and data mapper

Source: Internet
Author: User
Tags dsn rewind
PHP Object-oriented sample code sharing on domain model and data mapper

/* Here to explain because I am more lazy blog related article content more is to < in-depth PHP object-oriented, mode and Practice > A book Code collation and simple annotations to facilitate their future review and reference, interested in the relevant content of the beginner's friends suggest read the original text first. The content here can only be used as a learning supplement and reference. Thank you! Because the sample code for the domain model + data mapper in the original book is coherent, it's all sorted out here. Briefly introduce my view, from the point of view of database operation, the domain model is mainly a single record in the Operation data table, and the data mapper is the data that operates the whole data table. Interpretation by source The data mapper is a class responsible for mapping database data to objects, and the domain model symbolizes the individual actors in the real-world project, which typically behaves as a record in the data. Needless to say, the code and annotations are as follows: The three data-table structures related to the domain model are venue (venue), Space, event (events), respectively. CREATE TABLE ' venue ' (' id ' int (one) not null auto_increment, ' name ' text, primary key (' ID ')) CREATE table ' s Pace ' (' id ' int (one) not NULL auto_increment, ' venue ' int (one) default null, ' name ' text, primary key (' ID ') ) CREATE TABLE ' event ' (' id ' int (one) not null auto_increment, ' space ' int (one) default null, ' Start ' mediumte XT, ' duration ' int (one) default null, ' name ' text, primary key (' ID ')) *///domain model (here only a venue class was built to understand) namespace woo\        Domain;abstract class domainobject{//abstract base class private $id;    function construct ($id =null) {$this->id = $id; } functiOn GetId () {return $this->id;    }//The original book is not specifically implemented, it should be used to obtain the object's subordinate object, such as venue (venue) related space (spatial) object//specific code implementation should be queried from the database related data and call the collection class, the following see this class will have an understanding    And the implementation of this method should be placed in the subclass to the static function GetCollection ($type) {return array ();    } function collection () {return self::getcollection (Get_class ($this));    }}class Venue extends DomainObject {private $name;        Private $spaces;        function construct ($id = null, $name =null) {$this->name= $name; $this->spaces = self::getcollection (' \\woo\\domain\\space ');    Here should prove my above guess parent::construct ($id);    } function Setspaces (Spacecollection $spaces) {$this->spaces = $spaces;        } function Addspace (Space $space) {$this->spaces->add ($space);    $space->setvenue ($this);        } function SetName ($name _s) {$this->name = $name _s;    $this->markdirty (); } function GetName () {return $this->nAme  }}//Data Mapper (as the original interpretation data Mapper is a class responsible for mapping database data to Objects) namespace Woo\mapper;abstract class mapper{//abstract static        $PDO; The PDO object function construct () {if!isset (self:: $PDO) {$dsn = \woo\base\applicationregistry::get) of the operating database            DSN ();            if (Is_null ($DSN)) {throw new \woo\base\appexception ("No DNS");            } self:: $PDO = new \pdo ($DSN);        Self:: $PDO->setattribute (\pdo::attr_errmode,\pdo::errmode_exception); }} function CreateObject ($array) {//creates an array as an object in the domain model above $obj = $this->docreateobject (        $array);    Implement return $obj in subclasses; The function find ($id) {//Gets a piece of data from the database by ID and creates it as an object $this->selectstmt ()->exec        Ute (Array ($id));        $array = $this->selectstmt ()->fetch ();        $this->selectstmt ()->closecursor ();        if (!is_array ($array)) {return null; } if (!isset ($array[' id ')) {return null;        } $object = $this->createobject ($array);        return $object;    } function Insert (\woo\domain\domainobject $obj) {//Inserts the object data into the database $this->doinsert ($obj);    }//Abstract function Update (\woo\domain\domainobject $objet) that requires an abstraction of the methods implemented in subclasses;    protected abstract function Docreateobject (array $array);    protected abstract function selectstmt (); protected abstract function Doinsert (\woo\domain\domainobject $object);}    Here only a Venuemapper class is created to understand the class Venuemapper extends Mapper {function construct () {parent::construct ();        Various SQL statement objects $this->selectstmt = self:: $PDO->prepare ("select * from venue where id=?"); $this->updatestmt = self:: $PDO->prepare ("Update venue set name=?,id=?")        where id=? ");    $this->insertstmt = self:: $PDO->prepare ("INSERT into venue (name) VALUES (?)"); } protected function GetCollection (array $raw) {//Will spaceThe array is converted to object return new Spacecollection ($raw, $this); The base class for this class is below} protected function Docreateobject (array $array) {//create object $obj = new \woo\domain\        Venue ($array [' id ']);        $obj->setname ($array [' name ']);    return $obj;        } protected function Doinsert (\woo\domain\domainobject $object) {//Inserts the object into the database print ' inserting ';        Debug_print_backtrace ();        $values = Array ($object->getname ());        $this->insertstmt->execute ($values);        $id = self:: $PDO->lastinsertid ();    $object->setid ($id);        } function Update (\woo\domain\domainobject $object) {//Modify database Data print "updation\n";        $values = Array ($object->getname (), $object->getid (), $object->getid ());    $this->updatestmt->execute ($values);    } function Selectstmt () {//Returns an SQL statement object return $this->selectstmt; } The}/*iterator interface defines the method: Rewind () points to the list at the beginning of current (Returns the element at the current pointer key () returns the current key (for example, the pointer's finger) next () valid () This class is a multi-line record, passing the raw data and mapper taken out of the database,            The data mapper is then created as an object when the data is fetched */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 ($ma            Pper) {$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 (); The subclass implements the protected function notifyaccess () {///do not know what to do when inserting an object, the Private function GetRow ($nu        m) {//Gets a single piece of data in the collection, which is where the data is created by the data mapper as an object $this->notifyaccess ();        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 $mapper = new \woo\mapper\venuemapper (), $venue = $mapper->find;p rint_r ($venue); $venue = new \woo\domain\ Venue (); $venue->setname ("The Likey lounge-yy");//Insert the object into the database $mapper->insert ($venue);//read from the database the object you just inserted $venue = $ Mapper->find ($venue->getid ());p Rint_r ($venue);//Modify Object $venue->setname ("The Bibble beer likey lounge-yy");// Update the Record $mapper->update ($venue) by invoking update,//Read the object data again $venue = $mapper->find ($venue->getid ());p Rint_r ($venue) ;//End

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.