PHP面向对象之领域模型+数据映射器实例(分析)(2)

rewind()            指向列表开头   
current()            返回当前指针处的元素
key()                返回当前的键(比如,指针的指)
next()               
valid()

下面这个类是处理多行记录的,传递数据库中取出的原始数据和映射器进去,然后通过数据映射器在获取数据时将其创建成对象

abstract class Collection implements \Iterator{ protected $mapper; //数据映射器 protected $total = 0; //集合元素总数量 protected $raw = array(); //原始数据 private $result; private $pointer = 0; //指针 private $objects = array(); //对象集合 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){ //这里是直接添加对象 $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(){ //不知道干嘛的 } private function getRow($num){ //获取集合中的单条数据,就是这里通过数据映射器将数据创建成对象 $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(){ //获取当前指针对象 return $this->getRow($this->pointer); } public function key(){ //获取当前指针 return $this->pointer; } public function next(){ //获取当前指针对象,并将指针下移 $row = $this->getRow($this->pointer); if($row){$this->pointer ++} return $row; } public function valid(){ //验证 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"); //插入对象到数据库 $mapper->insert($venue); //从数据库中读出刚才插入的对象 $venue = $mapper->find($venue->getId()); print_r($venue); //修改对象 $venue->setName("the bibble beer likey lounge-yy"); //调用update来更新记录 $mapper->update($venue); //再次读出对象数据 $venue = $mapper->find($venue->getId()); print_r($venue); //结束

以上这篇PHP面向对象之领域模型+数据映射器实例(分析)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/6aa892af70062f16fb2fbb217a5951d0.html