PHP Object-oriented domain model + data Mapper instance graphics

Source: Internet
Author: User
Tags dsn rewind
This article mainly introduces the PHP object-oriented domain model + data Mapper instance graphics and text detailed, interested in the friend's reference, I hope to help you.

The code and annotations are as follows:

The three data table structures related to the domain model are venue (venue), space (spatial), event (events), respectively.

CREATE TABLE ' venue ' (   ' id ' int (one) not null auto_increment,   ' name ' text,   primary key (' ID ')) CREATE TABLE ' Spa Ce ' (   ' 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 ' mediumt Ext,   ' 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 objects, such as venue (venue) Related space objects//specific code implementation should be queried from the database related data and call the collection class, the following see this class will have a 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;    The}}//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 of the base class;      The PDO object function __construct () {if (!isset (self:: $PDO) {$dsn = \woo\base\applicationregistry::getdsn () of the operating database;      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 ()->execute (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) {//Converts space array 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; }  }

Iterator interface-defined methods:

Rewind () point to the beginning of the list
Current () returns the element at the present 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 () {///Don't know what to do} Private function GetRow ($num) {//Get a single in the collection when inserting an object in a subclass    Data, this is where the data is created by the data mapper $this->notifyaccess (); if ($num >= $this-&Gt;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->raw[$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 object to 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 ");//Call Update for Record $mapper->update ($venue);//Read 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.