Domain modeling base class

WBOY
Release: 2016-07-25 08:48:16
Original
1068 people have browsed it
Implemented lazy loading and registration as the only one
Java needs to introduce the concepts of factories and warehouses, while PHP only needs two or three lines of code to complete the same function
  1. /**
  2. * Domain model parent class
  3. * Implement delayed data loading and registration as unique
  4. * @author liuxu
  5. *
  6. */
  7. abstract class Domain
  8. {
  9. protected $_id;
  10. protected $_id2;
  11. protected $_fields = array();
  12. protected $_loadedById = false;
  13. static protected $_objs;
  14. private function __construct($id,$id2=0)
  15. {
  16. $this->_id = $id?$id:0;
  17. $this->_id2 = $id2?$id2: 0;
  18. }
  19. static public function factory($id,$id2=0)
  20. {
  21. $class = get_called_class();
  22. if(!isset(self::$_objs[$class][$id][$ id2]))//Register as unique
  23. {
  24. self::$_objs[$class][$id][$id2] = new $class($id,$id2);
  25. }
  26. return self::$ _objs[$class][$id][$id2];
  27. }
  28. public function load($fields=array())
  29. {
  30. if($fields)
  31. {
  32. foreach($fields as $key=> $value)
  33. {
  34. $this->_fields[$key] = $value;
  35. }
  36. }
  37. }
  38. public function wash()
  39. {
  40. $this->_fields = array();
  41. }
  42. //Load complete data
  43. abstract protected function loadById();
  44. public function __get($field)
  45. {
  46. if(!isset($this->_fields[$field]) && !$this-> _loadedById)
  47. {
  48. //Lazy loading
  49. $this->loadById();
  50. $this->_loadedById = true;
  51. }
  52. $value = isset($this->_fields[$field]) ?$this->_fields[$field]:null;
  53. return $value;
  54. }
  55. }
Copy code


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template