实现了延迟载入、注册为唯一 java要引入工厂和仓库的概念,而php只需要两三行代码就完成了同样的功能
- /**
- * 领域模型父类
- * 实现数据延迟载入、注册为唯一
- * @author liuxu
- *
- */
- abstract class Domain
- {
-
- protected $_id;
- protected $_id2;
-
- protected $_fields = array();
-
- protected $_loadedById = false;
-
- static protected $_objs;
-
- private function __construct($id,$id2=0)
- {
- $this->_id = $id?$id:0;
- $this->_id2 = $id2?$id2:0;
- }
-
- static public function factory($id,$id2=0)
- {
- $class = get_called_class();
- if(!isset(self::$_objs[$class][$id][$id2]))//注册为唯一
- {
- self::$_objs[$class][$id][$id2] = new $class($id,$id2);
- }
-
- return self::$_objs[$class][$id][$id2];
- }
-
- public function load($fields=array())
- {
- if($fields)
- {
- foreach($fields as $key=>$value)
- {
- $this->_fields[$key] = $value;
- }
- }
- }
-
- public function wash()
- {
- $this->_fields = array();
- }
-
- //载入完整数据
- abstract protected function loadById();
-
- public function __get($field)
- {
- if(!isset($this->_fields[$field]) && !$this->_loadedById)
- {
- //延迟载入
- $this->loadById();
- $this->_loadedById = true;
- }
-
- $value = isset($this->_fields[$field])?$this->_fields[$field]:null;
- return $value;
- }
-
-
-
- }
复制代码
|