PHP面向对象之选择工厂和更新工厂

  1. /*
  2. 选择工厂和更新工厂模式,这个模式的类(UpdateFactory和SelectionFactory类)就是用来创建SQL语句的.
  3. 因为涉及到之前学习的内容比较多,这里就尽量将之前相关模式的示例代码放在一起来进行学习和回顾了。
  4. 以下的代码都是代码片段而且涉及到连接数据库,无法进行整体的调试(某些部分单独拿出来的话就可以),因此重在理解。
  5. */
  6. //更新工厂
  7. abstract class UpdateFactory{
  8.     
  9.     abstract function newUpdate(woodomainDomainObject $obj);
  10.     
  11.     //拼接更新或插入的sql语句
  12.     protected function buildStatement($table,array $fields ,array $condition = null){
  13.         $terms = array(); //SQL语句中占位符所代表的实际值
  14.         if(!is_null($condition)){        //有条件则拼接更新语句,无条件则拼接插入语句
  15.             $query = "UPDATE {$table} SET";
  16.             $query .= implode(" = ? " ,array_keys($fields)) . " = ? ";
  17.             $terms = array_values($fields);
  18.             $cond = array();
  19.             $query .= " WHERE ";
  20.             foreach($condition as $key=>$val){
  21.                 $cond[] = " $key = ? ";
  22.                 $terms[] = $val;
  23.             }
  24.             $query .= implode(" AND ",$cond);
  25.         } else {
  26.             $query = " INSERT INTO {$table} (";
  27.             $query .= implode(",",array_keys($fields));
  28.             $query .= " ) VALUES ( ";
  29.             foreach($fields as $name => $value){
  30.                 $terms[] = $value;
  31.                 $qs[] = "?";
  32.             }
  33.             $query .= implode(",",$qs);
  34.             $query .=" ) ";
  35.         }
  36.         return array($query,$terms);
  37.     }
  38. }
  39. //通过领域模型生成SQL语句
  40. class VenueUpdateFactory extends UpdateFactory{
  41.     function newUpdate(woodomainDomainObject $obj){
  42.         $id = $obj->getId();
  43.         $cond = null;
  44.         $values['name'] = $obj->getName();
  45.         if($id > -1 ){
  46.             $cond["id"] = $id;
  47.         }
  48.         return $this->buildStatement("venue",$values,$cond);
  49.     }
  50. }
  51. //选择工厂
  52. abstract class SelectionFactory{
  53.     abstract function newSelection(IdentityObject $obj);
  54.     
  55.     //通过标识对象拼接sql语句的where条件语句
  56.     function buildWhere (IdentityObject $obj){
  57.         if($obj->isVoid){
  58.             return array("",array());
  59.         }
  60.         $compstrings = array();
  61.         $values = array();
  62.         foreach($obj->getComps() as $comp){
  63.             $compstrings[] = "{$comp['name']} {$comp['operator']} ?";
  64.             $values[] = $comp['value'];
  65.         }
  66.         $where =  " WHERE " . implode(" AND ",$compstrings);
  67.         return array($where,$values);
  68.     }
  69. }
  70. //拼接select语句
  71. class VenuSelectionFactory extends SelectionFactory {
  72.     function newSelection(IdentityObject $obj){
  73.         $field = implode(',',$obj->getObjectFields());
  74.         $core = "SELECT $fields FROM venue";
  75.         list($where,$values) = $this->buildWhere($obj);
  76.         return array($core." ".$where,$values);
  77.     }
  78. }
  79. //现在来回顾一下之前学习过的相关知识
  80. //字段对象
  81. class Field {
  82.     protected $name = null;          //字段名称
  83.     protected $operator = null;         //操作符    
  84.     protected $comps = array();         //存放条件的数组    
  85.     protected $incomplete = false;     //检查条件数组是否有值
  86.     
  87.     function __construct ($name){
  88.         $this->name= $name;
  89.     }
  90.     
  91.     //添加where 条件
  92.     function addTest($operator,$value){
  93.         $this->comps[] = array('name'=>$this->name,'operator'=>$operator,'value'=>$value);
  94.     }
  95.     
  96.     //获取存放条件的数组
  97.     function getComps(){
  98.         return $this->comps;
  99.     }
  100.     
  101.     function isIncomplete(){
  102.         return empty($this->comps);
  103.     }
  104. }
  105. //标识对象,主要功能就是拼接where条件语句
  106. class IdentityObject {
  107.     protected $currentfield = null;        //当前操作的字段对象
  108.     protected $fields = array();        //字段对象集合
  109.     private $and = null;
  110.     private $enforce = array();            //限定的合法字段        
  111.     
  112.     function __construct($field = null, array $enforce = null){
  113.         if(!is_null($enforce)){
  114.             $this->enforce = $enforce;
  115.         }
  116.         if(!is_null($field)){
  117.             $this->field($field);
  118.         }
  119.     }
  120.     
  121.     //获取限定的合法字段
  122.     function getObjectFields(){
  123.         return $this->enforce;
  124.     }
  125.     
  126.     //主要功能为设置当前需要操作的字段对象
  127.     function field($fieldname){
  128.         if(!$this->isVoid()&& $this->currentfield->isIncomplete()){
  129.             throw new Exception("Incomplete field");
  130.         }
  131.         $this->enforceField($fieldname);
  132.         if(isset($this->fields[$fieldname]){
  133.             $this->currentfield = $this->fields[$fieldname];
  134.         } else {
  135.             $this->currentfield = new Field($fieldname);
  136.             $this->fields[$fieldname] = $this->currentfield;
  137.         }
  138.         return $this;                    //采用连贯语法
  139.     }
  140.     
  141.     //字段集合是否为空
  142.     function isVoid(){
  143.         return empty($this->fields);
  144.     }
  145.     
  146.     //检查字段是否合法
  147.     function enforceField ($fieldname){
  148.         if(!in_array($fieldname,$this->enforce) && !empty($this->enforce)){
  149.             $forcelist = implode(',',$this->enforce);
  150.             throw new Exception("{$fieldname} not a legal field {$forcelist}");
  151.         }
  152.     }
  153.     
  154.     
  155.     //向字段对象添加where条件
  156.     function eq($value){
  157.         return $this->operator("=",$value);
  158.     }
  159.     
  160.     function lt($value){
  161.         return $this->operator("<",$value);
  162.     }
  163.     
  164.     function gt($value){
  165.         return $this->operator(">",$value);
  166.     }
  167.     
  168.     //向字段对象添加where条件
  169.     private function operator($symbol,$value){
  170.         if($this->isVoid){
  171.             throw new Exception("no object field defined");
  172.         }
  173.         $this->currentfield->addTest($symbol,$value);
  174.         return $this;                                     //采用连贯语法
  175.     }
  176.     
  177.     //获取此类中所有字段对象集合的where条件数组
  178.     function getComps(){
  179.         $ret = array();
  180.         foreach($this->fields as $key => $field){
  181.             $ret = array_merge($ret,$field->getComps());
  182.         }
  183.         return $ret;
  184.     }
  185. }
  186. //数据映射器
  187. class DomainObjectAssembler {
  188.     protected static $PDO;
  189.     
  190.     //PersistenceFactory本例中并未实现,按原书的说法读者自己完成
  191.     //其主要功能就是生成相应类型的选择工厂类、更新工厂类或Collection对象
  192.     //在初始化的时候根据传入的PersistenceFactory对象决定了这个类是映射那个数据库表和领域模型的
  193.     function __construct (PersistenceFactory $factory){
  194.         $this->factory = $factory;
  195.         if(!isset(self::$PDO)){
  196.             $dsn = wooaseApplicationRegistry::getDSN();
  197.             if(is_null($dsn)){
  198.                 throw new wooaseAppException("NO DSN");
  199.             }
  200.             self::$PDO = new PDO ($dsn);
  201.             self::$PDO->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  202.         }
  203.     }
  204.     
  205.     //获取预处理对象,用sql语句本身做为对象数组的键
  206.     function getStatement($str){
  207.         if(!isset($this->statements[$str])){
  208.             $this->statements[$str] = self::$PDO->prepare($str);
  209.         }
  210.         return $this->statements[$str];
  211.     }
  212.     
  213.     //根据where条件返回一条数据
  214.     function findOne(IdentityObject $idobj){
  215.         $collection = $this->find($idobj);
  216.         return $collection->next();
  217.     }
  218.     
  219.     //根据where条件返回一个数据集合
  220.     function find(IdentityObject $idobj){
  221.         $selfact = $this->factory->getSelectionFactory();             //获取选择工厂对象
  222.         list($selection,$values) = $selfact->newSelection($idobj);    //获取sql语句
  223.         $stmt = $this->getStatement($selection);                    //获取预处理对象
  224.         $stmt->execute($values);                    
  225.         $raw = $stmt->fetchAll();
  226.         return $this->factory->getCollection($raw);                    //还记得Collection对象吗,下面粘出代码回顾一下
  227.     }
  228.     
  229.     //根据where条件插入或更新一条数据
  230.     function insert(woodomainDomainObject $obj){
  231.         $upfact = $this->factory->getUpdateFactory();        //获取更新工厂对象
  232.         list($update,$values) = $upfact->newUpdate($obj);    //获取sql语句
  233.         $stmt = $this->getStatement($update);                //获取预处理对象
  234.         $stmt->execute($values);
  235.         if($obj->getId()<0){                                    
  236.             $obj->setId(self::$PDO->lastInsertId);
  237.         }
  238.         $obj->markClean();
  239.     }
  240.     
  241.     
  242. }
  243. /*
  244. 这里在回顾一下Collection类,当然这个类和上面使用的Collection类是有差别的,因为至少这里的Mapper类与之前相比发生了一些变化
  245. Iterator接口定义的方法:
  246. rewind()            指向列表开头    
  247. current()            返回当前指针处的元素
  248. key()                返回当前的键(比如,指针的指)
  249. next()                
  250. valid()
  251. 下面这个类是处理多行记录的,传递数据库中取出的原始数据和映射器进去,然后通过数据映射器在获取数据时将其创建成对象
  252. */
  253. abstract class Collection implements Iterator{
  254.     protected $mapper;            //数据映射器
  255.     protected $total = 0;        //集合元素总数量
  256.     protected $raw = array();    //原始数据
  257.     
  258.     private $result;
  259.     private $pointer = 0;        //指针
  260.     private $objects = array();    //对象集合
  261.     
  262.     function __construct (array $raw = null,Mapper $mapper= null){
  263.         if(!is_null($raw)&& !is_null($mapper)){
  264.             $this->raw = $raw;
  265.             $this->total = count($raw);
  266.         }
  267.         $this->mapper = $mapper;
  268.     }
  269.     
  270.     function add(woodomainDmainObject $object){    //这里是直接添加对象
  271.         $class = $this->targetClass();
  272.         if(!($object instanceof $class)){
  273.             throw new Exception("This is a {$class} collection");
  274.         }
  275.         $this->notifyAccess();
  276.         $this->objects[$this->total] = $object;
  277.         $this->total ++;
  278.     }
  279.     
  280.     abstract function targetClass();    //子类中实现用来在插入对象时检查类型的
  281.     
  282.     protected function notifyAccess(){    //不知道干嘛的
  283.         
  284.     }
  285.     
  286.     private function getRow($num){        //获取集合中的单条数据,就是这里通过数据映射器将数据创建成对象
  287.         $this->notifyAccess();
  288.         if($num >= $this->total || $num < 0){
  289.             return null;
  290.         }
  291.         if(isset($this->objects[$num]){
  292.             return $this->objects[$num];
  293.         }
  294.         if(isset($this->raw[$num]){
  295.             $this->objects[$num] = $this->mapper->createObject($this->raw[$num]);
  296.             return $this->objects[$num];
  297.         }
  298.     }
  299.     
  300.     public function rewind(){            //重置指针
  301.         $this->pointer = 0;
  302.     }
  303.     
  304.     public function current(){            //获取当前指针对象
  305.         return $this->getRow($this->pointer);
  306.     }
  307.     
  308.     public function key(){                //获取当前指针
  309.         return $this->pointer;
  310.     }
  311.     
  312.     public function next(){            //获取当前指针对象,并将指针下移    
  313.         $row = $this->getRow($this->pointer);
  314.         if($row){$this->pointer ++}
  315.         return $row;
  316.     }
  317.     
  318.     public function valid(){        //验证
  319.         return (!is_null($this->current()));
  320.     }
  321.     
  322. }
  323. //子类
  324. class VenueColletion extends Collection implements woodomainVenueCollection{
  325.     function targetClass(){
  326.         return "woodomainVenue";
  327.     }
  328. }
  329. //客户端
  330. //初始化一个能够获取venue类型的选择工厂类、更新工厂类或Collection对象的超级工厂类
  331. $factory = woomapperPersistenceFactory::getFactory("woo\domain\Venue");    
  332. $finder = new woomapperDomainObjectAssembler($factory);        //数据映射器
  333. $idobj = $factory->getIdentityObject()->field('name')->eq('The Eyeball Inn');    //设置where条件语句
  334. $collection = $finder->find($idobj);                    //根据where条件查找一个数据集合(一个Collection对象)
  335. foreach($collection as $venue){                            
  336.     print $venue->getName()." ";
  337. }
原文地址:https://www.cnblogs.com/shishicai/p/7238800.html