|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace DesignPatterns; |
| 4 | + |
| 5 | +/** |
| 6 | + * Proxy pattern |
| 7 | + * |
| 8 | + * Purpose: |
| 9 | + * to interface to anything that is expensive or impossible to duplicate |
| 10 | + * |
| 11 | + * Examples: |
| 12 | + * - Doctrine2 uses proxies to implement framework magic (e.g. Lazy initialization) in them, while the user still works |
| 13 | + * with his own entity classes and will never use nor touch the proxies |
| 14 | + * |
| 15 | + */ |
| 16 | +class Record |
| 17 | +{ |
| 18 | + protected $_data; |
| 19 | + |
| 20 | + public function __construct($data = null) |
| 21 | + { |
| 22 | + $this->_data = $data; |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * magic setter |
| 27 | + * |
| 28 | + * @param string $name |
| 29 | + * @param mixed $value |
| 30 | + * @return void |
| 31 | + */ |
| 32 | + public function __set($name, $value) |
| 33 | + { |
| 34 | + $this->_data[(string) $name] = $value; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * magic getter |
| 39 | + * |
| 40 | + * @param string $name |
| 41 | + * @return mixed|null |
| 42 | + */ |
| 43 | + public function __get($name) |
| 44 | + { |
| 45 | + if (array_key_exists($name, $this->_data)) { |
| 46 | + return $this->_data[(string) $name]; |
| 47 | + } else { |
| 48 | + return null; |
| 49 | + } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +class RecordProxy extends Record |
| 54 | +{ |
| 55 | + /** |
| 56 | + * @var bool |
| 57 | + */ |
| 58 | + protected $_isDirrty = false; |
| 59 | + |
| 60 | + /** |
| 61 | + * @var bool |
| 62 | + */ |
| 63 | + protected $_isInitialized = false; |
| 64 | + |
| 65 | + /** |
| 66 | + * @param array |
| 67 | + */ |
| 68 | + public function __construct($data) |
| 69 | + { |
| 70 | + parent::__construct($data); |
| 71 | + |
| 72 | + // when the record has data, mark it as initialized |
| 73 | + // since Record will hold our business logic, we don't want to |
| 74 | + // implement this behaviour there, but instead in a new proxy class |
| 75 | + // that extends the Record class |
| 76 | + if (null !== $data) { |
| 77 | + $this->_isInitialized = true; |
| 78 | + $this->_isDirrty = true; |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * magic setter |
| 84 | + * |
| 85 | + * @param string $name |
| 86 | + * @param mixed $value |
| 87 | + * @return void |
| 88 | + */ |
| 89 | + public function __set($name, $value) |
| 90 | + { |
| 91 | + $this->_isDirrty = true; |
| 92 | + parent::__set($name, $value); |
| 93 | + } |
| 94 | +} |
0 commit comments