溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PHP面向?qū)ο蟮念I(lǐng)域模型+數(shù)據(jù)映射器實(shí)例介紹

發(fā)布時(shí)間:2021-09-07 15:44:11 來(lái)源:億速云 閱讀:146 作者:Yi 欄目:開(kāi)發(fā)技術(shù)

PHP面向?qū)ο蟮念I(lǐng)域模型+數(shù)據(jù)映射器實(shí)例介紹,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。

因原書(shū)中領(lǐng)域模型+數(shù)據(jù)映射器的示例代碼是連貫在一起的 所以這里就整理在一起了。

簡(jiǎn)單介紹一下我的看法,從數(shù)據(jù)庫(kù)操作的角度看領(lǐng)域模型主要是操作數(shù)據(jù)表中的單條記錄的而數(shù)據(jù)映射器是操作整個(gè)數(shù)據(jù)表的數(shù)據(jù)的。

按原文的解釋數(shù)據(jù)映射器是一個(gè)負(fù)責(zé)將數(shù)據(jù)庫(kù)數(shù)據(jù)映射到對(duì)象的類,而領(lǐng)域模型象征著真實(shí)世界里項(xiàng)目中的各個(gè)參與者,它在數(shù)據(jù)中通常表現(xiàn)為一條記錄。

廢話不多說(shuō),代碼和注解如下:

與領(lǐng)域模型相關(guān)的三個(gè)數(shù)據(jù)表結(jié)構(gòu)分別為venue(場(chǎng)所)、space(空間)、event(事件)。

create table 'venue' (
   'id' int(11) not null auto_increment,
   'name' text,
   primary key ('id')
)
create table 'space' (
   'id' int(11) not null auto_increment,
   'venue' int(11) default null,
   'name' text,
   primary key ('id')
)
create table 'event' (
   'id' int(11) not null auto_increment,
   'space' int(11) default null,
   'start' mediumtext,
   'duration' int(11) default null,
   'name' text,
   primary key ('id')
)
//領(lǐng)域模型(這里只建了一個(gè)Venue類用于理解)
namespace woo\domain;

abstract class DomainObject{      //抽象基類
  
  private $id;
  
  function __construct ($id=null){
    $this->id = $id;
  }
  
  function getId(){
    return $this->id;
  }
  
  //原書(shū)沒(méi)有具體實(shí)現(xiàn),應(yīng)該是用于獲取對(duì)象的從屬對(duì)象的,比如venue(場(chǎng)所)相關(guān)的space(空間)對(duì)象
  //具體的代碼實(shí)現(xiàn)中應(yīng)該從數(shù)據(jù)庫(kù)中查詢了相關(guān)數(shù)據(jù)并調(diào)用了Collection類,下面看到這個(gè)類的時(shí)候會(huì)有一個(gè)了解
  //而且這個(gè)方法的實(shí)現(xiàn)應(yīng)該放在子類中才對(duì)
  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'); //這里應(yīng)該證明了我上述的猜測(cè)
    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;
  }
}


//數(shù)據(jù)映射器(正如原文的解釋數(shù)據(jù)映射器是一個(gè)負(fù)責(zé)將數(shù)據(jù)庫(kù)數(shù)據(jù)映射到對(duì)象的類)
namespace woo\mapper;

abstract class Mapper{      //抽象基類
  abstract static $PDO;    //操作數(shù)據(jù)庫(kù)的pdo對(duì)象
  function __construct (){
    if(!isset(self::$PDO){
      $dsn = \woo\base\ApplicationRegistry::getDSN();
      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){          //將數(shù)組創(chuàng)建為上述領(lǐng)域模型中的對(duì)象
    $obj = $this->doCreateObject($array);    //在子類中實(shí)現(xiàn)
    return $obj;
  }
  
  function find($id){                //通過(guò)ID從數(shù)據(jù)庫(kù)中獲取一條數(shù)據(jù)并創(chuàng)建為對(duì)象
    $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){      //將對(duì)象數(shù)據(jù)插入數(shù)據(jù)庫(kù)
    $this->doInsert($obj);
  }
  
  //需要在子類中實(shí)現(xiàn)的各抽象方法
  abstract function update(\woo\domain\DomainObject $objet);
  protected abstract function doCreateObject(array $array);
  protected abstract function selectStmt();
  protected abstract function doInsert(\woo\domain\DomainObject $object);
}

//這里只建立一個(gè)VenueMapper類用于理解
class VenueMapper extends Mapper {
  function __construct (){    
    parent::__construct();  //各種sql語(yǔ)句對(duì)象  
    $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){    //將Space數(shù)組轉(zhuǎn)換成對(duì)象
    return new SpaceCollection($raw,$this);      //這個(gè)類的基類在下面    
  }
  
  protected function doCreateObject (array $array){  //創(chuàng)建對(duì)象
    $obj = new \woo\domain\Venue($array['id']);
    $obj->setname($array['name']);
    return $obj;
  }
  
  protected function doInsert(\woo\domain\DomainObject $object){ //將對(duì)象插入數(shù)據(jù)庫(kù)
    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){    //修改數(shù)據(jù)庫(kù)數(shù)據(jù)
    print "updation\n";
    $values = array($object->getName(),$object->getId(),$object->getId());
    $this->updateStmt->execute($values);
  }
  
  function selectStmt(){          //返回一個(gè)sql語(yǔ)句對(duì)象
    return $this->selectStmt;
  }
  
}

Iterator接口定義的方法:

rewind()            指向列表開(kāi)頭   
current()            返回當(dāng)前指針處的元素
key()                返回當(dāng)前的鍵(比如,指針的指)
next()               
valid()

下面這個(gè)類是處理多行記錄的,傳遞數(shù)據(jù)庫(kù)中取出的原始數(shù)據(jù)和映射器進(jìn)去,然后通過(guò)數(shù)據(jù)映射器在獲取數(shù)據(jù)時(shí)將其創(chuàng)建成對(duì)象

abstract class Collection implements \Iterator{
  protected $mapper;      //數(shù)據(jù)映射器
  protected $total = 0;    //集合元素總數(shù)量
  protected $raw = array();  //原始數(shù)據(jù)
  
  private $result;
  private $pointer = 0;    //指針
  private $objects = array();  //對(duì)象集合
  
  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){  //這里是直接添加對(duì)象
    $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();  //子類中實(shí)現(xiàn)用來(lái)在插入對(duì)象時(shí)檢查類型的
  
  protected function notifyAccess(){  //不知道干嘛的
    
  }
  
  private function getRow($num){    //獲取集合中的單條數(shù)據(jù),就是這里通過(guò)數(shù)據(jù)映射器將數(shù)據(jù)創(chuàng)建成對(duì)象
    $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->raw[$num]);
      return $this->objects[$num];
    }
  }
  
  public function rewind(){      //重置指針
    $this->pointer = 0;
  }
  
  public function current(){      //獲取當(dāng)前指針對(duì)象
    return $this->getRow($this->pointer);
  }
  
  public function key(){        //獲取當(dāng)前指針
    return $this->pointer;
  }
  
  public function next(){      //獲取當(dāng)前指針對(duì)象,并將指針下移  
    $row = $this->getRow($this->pointer);
    if($row){$this->pointer ++}
    return $row;
  }
  
  public function valid(){    //驗(yàn)證
    return (!is_null($this->current()));
  }
  
}

//子類
class VenueColletion extends Collection implements \woo\domain\VenueCollection{
  function targetClass(){
    return "\woo\domain\Venue";
  }
}


//客戶端
$mapper = new \woo\mapper\VenueMapper();
$venue = $mapper->find(12);
print_r($venue);

$venue = new \woo\domain\Venue();
$venue->setName("the likey lounge-yy");
//插入對(duì)象到數(shù)據(jù)庫(kù)
$mapper->insert($venue);
//從數(shù)據(jù)庫(kù)中讀出剛才插入的對(duì)象
$venue = $mapper->find($venue->getId());
print_r($venue);

//修改對(duì)象
$venue->setName("the bibble beer likey lounge-yy");
//調(diào)用update來(lái)更新記錄
$mapper->update($venue);
//再次讀出對(duì)象數(shù)據(jù)
$venue = $mapper->find($venue->getId());
print_r($venue);


//結(jié)束

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI