PHP Object-oriented unit of work

Source: Internet
Author: User
Tags map class
The following small series for everyone to bring a PHP object-oriented work unit (example). Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.

Unit of work

This pattern involves the domain model, the data mapper, and the identity map, which are collated and reviewed in a unified way.

$venue = new \woo\domain\venue (null, "The Green Tree");

\woo\domain\objectwatcher::instance ()->performoperations ();

Now take the above two lines of client code as a pointcut roughly describe how this pattern works.

The first sentence when you create an object using a domain model object, it invokes the identity map Objectwatcher class

Mark yourself as a new object that needs to be added. The Performoperations method of the second sentence will be saved in the object that identifies the property $new of the Mapper

Inserted into the database. Note that it internally calls the $obj->finder () method to generate a corresponding data mapper class from the Helperfactory factory class in the realm pattern and return it.

Helperfactory This class does not have a specific implementation (the original is not implemented), in fact, according to the type of the class passed by the parameter to create the corresponding data mapper using the conditional branch.

Read the code and comments directly below to understand.


Namespace woo\domain;//identity Map class objectwatcher{Private $all = Array ();      Store object's small warehouse private $dirty = Array ();        Store objects that need to be modified in the database private $new = Array ();      Store objects that need to be added to the database private $delete = Array ();      Store objects that need to be deleted in the database private static $instance; Singleton private Function construct () {} static function instance () {if (!self:: $instance) {self:: $instance = n    EW Objectwatcher ();  } return Self:: $instance; }//Gets a unique identity, where the domain class class name +id is used to create a unique identity that avoids duplicate ID problems when multiple database tables call this class function Globalkey (DomainObject $obj) {$key = Get_cl ($obj). "." .    $obj->getid ();  return $key;    }//Add object static function Add (DomainObject $obj) {$inst = Self::instance ();  $inst->all[$inst->globalkey ($obj)] = $obj;    }//Gets the object static function exists ($classname, $id) {$inst = Self::instance ();    $key = "$classname. $id";    if (Isset ($inst->all[$key]) {return $inst->all[$key];  } return null; }//marked as the object to be deleted static function AdddeletE (DomainObject $obj) {$self = Self::instance ();  $self->delete[$self->globalkey ($obj)] = $obj;    }//marked as the object that needs to be modified static function Adddirty (DomainObject $obj) {$inst = Self::instance ();    if (!in_array ($obj, $inst->new,true)) {$inst->dirty[$inst->globalkey ($obj)] = $obj;    }}//is marked as requiring new object static function AddNew (DomainObject $obj) {$inst = Self::instance ();  $inst->new[] = $obj;    }//marked as Clean object static function Addclean (DomainObject $obj) {$self = Self::instance ();    unset ($self->delete[$self->globalkey ($obj)]);    unset ($self->dirty[$self->globalkey ($obj)]); $self->new = Array_filter ($self->new,function ($a) use ($obj) {return! (  $a = = = $obj);}); }//The object that needs to be deleted and changed above and the database interacts with the data handler function Performoperations () {foreach ($this->dirty as $key + $obj) {$obj-&G    T;finder ()->update ($obj);    $obj->finder () Gets a data mapper} foreach ($this->new as $key + = $obj) {$obj->finder ()->insert ($obj);  }  $this->dirty = Array ();  $this->new = Array ();    }}//domain Model abstract class domainobject{//abstract base class Private $id =-1;      function construct ($id =null) {if (Is_null ($id)) {$this->marknew ();    It is marked as needing new object when initializing} else {$this->id = $id;  }}//called method function Marknew () {objectwatcher::addnew ($this) that identifies the mapped tag object;  } function markdeleted () {objectwatcher::adddelete ($this);  } function Markdirty () {objectwatcher::adddirty ($this);  } function Markclean () {Objectwatcher::addclean ($this);  } function SetId ($id) {$this->id = $id;  } function GetId () {return $this->id;  } function Finder () {return Self::getfinder (Get_class ($this)); }//Use a factory class to instantiate a particular type of data mapper object, such as Venuemapper//This object will be called by the Performoperations method in the identity mapper to modify the operation of the database interaction static function  Getfinder ($type) {return helperfactory::getfinder ($type);  }}class Venue extends DomainObject {private $name;    Private $spaces; function construct ($id = null, $name =null) {$this->name= $name;     $this->spaces = self::getcollection (' \\woo\\domain\\space ');  Parent::construct ($id);    } function Setspaces (Spacecollection $spaces) {$this->spaces = $spaces;            $this->markdirty ();    The object marked as needing modification} function Addspace (Space $space) {$this->spaces->add ($space);    $space->setvenue ($this);            $this->markdirty ();    The object marked as needing modification} function SetName ($name _s) {$this->name = $name _s;            $this->markdirty ();  Object marked as needing to be modified} function GetName () {return $this->name;    }}//domain Model class Space extends domainobject{//... function setName ($name _s) {$this->name = $name _s;  $this->markdirty ();    } function Setvenue (Venue $venue) {$this->venue = $venue;  $this->markdirty ();    }}//Data Mapper abstract class mapper{abstract static $PDO; 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); }}//Gets the Tagged object private function getfromap ($id) {return \woo\domain\objectwatcher::exists ($this->targetclass (), $i  D); }//New Tagged object private function addtomap (\woo\domain\domainobject $obj) {//////return \woo\domain\objectwatcher::add  ($obj);    }//Map database data to Object function CreateObject ($array) {$old = $this->getfrommap ($array [' id ']);    if ($old) {return $old;}    $obj = $this->docreateobject ($array);    $this->addtomap ($obj);    $obj->markclean ();  return $obj;            The function find ($id) {//Gets a piece of data from the database by ID and creates it as an object $old = $this->getfrommap ($id);    if ($old) {return $old} $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);              $this->addtomap ($object);    return $object;    } function Insert (\woo\domain\domainobject $obj) {//Inserts the object data into the database $this->doinsert ($obj);              $this->addtomap ($obj);                    }//Abstract function Targetclass (), which needs to be implemented in subclasses;        Gets the type of the class, abstract function update (\woo\domain\domainobject $objet);        Modify Operation protected abstract function Docreateobject (array $array);                Create object protected abstract function selectstmt ();  Query operation protected abstract function Doinsert (\woo\domain\domainobject $object);      Insert Operation}class Venuemapper extends Mapper {function construct () {parent::construct ();    Preprocessing object $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 collection return new Spacecollection ($raw, $this);    } 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 a Preprocessed object return $this->selectstmt; }}//Client $venue = new \woo\domAin\venue (NULL, "The Green Tree");  is marked as a new object at initialization $venue->addspace (new \woo\domain\space (null, "The Space Upstairs")); This two-line Addspace method is not marked as a modification object because venue has been marked new, but Space is marked as a new object $venue->addspace when initialized (the new \woo\domain\space (null      , "the Bar Stage");      \woo\domain\objectwatcher::instance ()->performoperations (); Interact with database add a venue data, and two space data


This PHP object-oriented work unit (example) is a small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we support the script house a lot.

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.