function setSpaces(SpaceCollection $spaces){
$this->spaces = $spaces;
$this->markDirty(); //标记为需要修改的对象
}
function addSpace(Space $space){
$this->spaces->add($space);
$space->setVenue($this);
$this->markDirty(); //标记为需要修改的对象
}
function setName($name_s){
$this->name = $name_s;
$this->markDirty(); //标记为需要修改的对象
}
function getName(){
return $this->name;
}
}
//领域模型
class Space extends DomainObject{
//.........
function setName($name_s){
$this->name = $name_s;
$this->markDirty();
}
function setVenue(Venue $venue){
$this->venue = $venue;
$this->markDirty();
}
}
//数据映射器
abstract class Mapper{
abstract static $PDO; //操作数据库的pdo对象
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);
}
}
//获取标记的对象
private function getFroMap($id){
return \woo\domain\ObjectWatcher::exists($this->targetClass(),$id);
}
//新增标记的对象
private function addToMap(\woo\domain\DomainObject $obj){//////
return \woo\domain\ObjectWatcher::add($obj);
}
function insert(\woo\domain\DomainObject $obj){ //将对象数据插入数据库
$this->doInsert($obj);
$this->addToMap($obj);
}
//需要在子类中实现的各个抽象方法
abstract function targetClass(); //获取类的类型
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); //插入操作
}
class VenueMapper extends Mapper {
function __construct (){
parent::__construct();
//预处理对象
$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 \woo\domain\Venue($array['id']);
$obj->setname($array['name']);
return $obj;
}