实现了延迟载入、注册为唯一 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;
- }
-
-
-
- }
复制代码
|
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31