总结领域模型+数据映射器的实例

夜萱同学_7607

夜萱同学_7607

2017-06-23

1009人浏览

原创

Build MCP servers and clients for PHP applications with the official PHP SDK
Build MCP servers and clients for PHP applications with the official PHP SDK

使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

下载
/*这里要说明一下 因为本人比较懒 博客中相关文章的内容更多的是对一书中代码的整理和简单注解方便自己日后复习和参考,
对相关内容感兴趣的初学的朋友建议请先阅读原文。此处的内容只能当成一种学习的补充和参考。谢谢!
因原书中领域模型+数据映射器的示例代码是连贯在一起的 所以这里就整理在一起了。
简单介绍一下我的看法,从数据库操作的角度看领域模型主要是操作数据表中的单条记录的而数据映射器是操作整个数据表的数据的。
按原文的解释数据映射器是一个负责将数据库数据映射到对象的类,而领域模型象征着真实世界里项目中的各个参与者,它在数据中通常表现为一条记录。
废话不多说,代码和注解如下:

与领域模型相关的三个数据表结构分别为venue(场所)、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')
)*///领域模型(这里只建了一个Venue类用于理解)namespace woodomain;abstract class DomainObject{            //抽象基类private $id;    function __construct ($id=null){$this->id = $id;
    }    function getId(){return $this->id;
    }    //原书没有具体实现,应该是用于获取对象的从属对象的,比如venue(场所)相关的space(空间)对象
    //具体的代码实现中应该从数据库中查询了相关数据并调用了Collection类,下面看到这个类的时候会有一个了解
    //而且这个方法的实现应该放在子类中才对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'); //这里应该证明了我上述的猜测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;
    }
}//数据映射器(正如原文的解释数据映射器是一个负责将数据库数据映射到对象的类)namespace  woomapper;abstract class Mapper{            //抽象基类abstract static $PDO;        //操作数据库的pdo对象function __construct (){if(!isset(self::$PDO){$dsn = wooaseApplicationRegistry::getDSN();if(is_null($dsn)){throw new wooaseAppException("no dns");
            }
            self::$PDO = new PDO($dsn);
            self::$PDO->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        }
    }    function createObject($array){                    //将数组创建为上述领域模型中的对象$obj = $this->doCreateObject($array);        //在子类中实现return $obj;
    }    function find($id){                                //通过ID从数据库中获取一条数据并创建为对象$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(woodomainDomainObject $obj){            //将对象数据插入数据库$this->doInsert($obj);
    }    //需要在子类中实现的各抽象方法abstract function update(woodomainDomainObject $objet);protected abstract function doCreateObject(array $array);protected abstract function selectStmt();protected abstract function doInsert(woodomainDomainObject $object);
}//这里只建立一个VenueMapper类用于理解class VenueMapper extends Mapper {function __construct (){        
        parent::__construct();    //各种sql语句对象    $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数组转换成对象return new SpaceCollection($raw,$this);            //这个类的基类在下面            }    protected function doCreateObject (array $array){    //创建对象$obj = new woodomainVenue($array['id']);$obj->setname($array['name']);return $obj;
    }    protected function doInsert(woodomainDomainObject $object){  //将对象插入数据库print 'inserting';debug_print_backtrace();$values = array($object->getName());$this->insertStmt->execute($values);$id = self::$PDO->lastInsertId();$object->setId($id);
    }    function update(woodomainDomainObject $object){        //修改数据库数据print "updation
";$values = array($object->getName(),$object->getId(),$object->getId());$this->updateStmt->execute($values);
    }    function selectStmt(){                    //返回一个sql语句对象return $this->selectStmt;
    }
    
}/*Iterator接口定义的方法:
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(woodomainDmainObject $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 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 woodomainVenueCollection{function targetClass(){return "woodomainVenue";
    }
}//客户端$mapper = new woomapperVenueMapper();$venue = $mapper->find(12);print_r($venue);$venue = new woodomainVenue();$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速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

php

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Go-Zero API开发使用教程
Go-Zero API开发使用教程

本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。

2026.11.12

140

15

Go-Zero安装与goctl环境配置教程
Go-Zero安装与goctl环境配置教程

本专题围绕Go-Zero的安装与工具链配置展开,讲清Go版本要求、goctl安装方式、代理镜像、protoc依赖与环境变量设置,说明多版本共存、升级回退与CI流水线安装的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.12

100

15

Go-Zero零基础入门教程
Go-Zero零基础入门教程

本专题整理Go-Zero的入门知识,从框架定位、环境准备到跑通第一个API服务,讲清目录分层、配置加载、日志与中间件的基本用法,并对比Gin、Kratos的差异,帮助Go开发者建立整体认知,判断它是否适合当前项目。

2026.11.12

80

15

Postman身份认证怎么配置
Postman身份认证怎么配置

本专题从实际API接口调试场景出发,讲解Postman身份认证的完整配置流程,包括常见认证协议介绍、授权参数设置、访问令牌填写、OAuth 2.0授权及认证失败排查,帮助用户正确完成接口授权与访问验证。

2026.11.06

160

12

Postman请求头Headers怎么设置
Postman请求头Headers怎么设置

围绕Postman HTTP请求头配置展开,讲解Headers选项的具体使用方式,包括Key和Value参数填写、请求头信息添加、常见Header字段设置及请求头修改方法,帮助用户解决接口调试过程中遇到的请求头配置问题。

2026.11.06

140

13

Postman接口请求发送教程
Postman接口请求发送教程

详细介绍Postman接口请求的创建与发送方法,涵盖GET和POST请求、URL配置、请求参数、Headers请求头、Body请求体设置以及响应结果查看,帮助用户掌握Postman接口请求的完整操作流程。

2026.11.06

120

10

DBeaver怎么导入数据
DBeaver怎么导入数据

DBeaver数据导入专题,整理Excel、CSV、SQL、TXT等常见文件的数据导入方法,涵盖目标数据库选择、数据表创建、字段映射、数据类型设置及导入参数配置等操作,帮助用户将本地文件中的数据写入数据库,并了解批量导入、重复数据处理和导入失败等常见问题的解决方法。

2026.11.05

120

12

DBeaver安全防护教程大全
DBeaver安全防护教程大全

DBeaver安全防护专题,围绕数据库连接安全、账号密码保护和访问权限管理展开,整理SSL/TLS加密连接、SSH隧道、数据库凭据保存及证书验证等配置方法,同时介绍敏感信息保护、远程连接风险和高权限账号使用等注意事项,帮助用户提高数据库日常管理的安全性。

2026.11.05

100

12

DBeaver连接创建与配置教程
DBeaver连接创建与配置教程

本专题聚焦DBeaver数据库连接配置与管理,覆盖从新建连接、选择数据库类型到填写连接参数和验证连接的完整流程。针对MySQL、PostgreSQL、SQL Server等常见数据库,整理相应的连接设置方法,并提供驱动缺失、认证失败和连接异常等问题的排查方向。

2026.11.04

120

16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
墨刀帮助中心
墨刀帮助中心

共0课时 | 0人学习

MyEclipse学习中心
MyEclipse学习中心

共0课时 | 0人学习

Apache Subversion 官方手册
Apache Subversion 官方手册

共0课时 | 0人学习