Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php  | 
            ||
| 10 | class ValueProxy  | 
            ||
| 11 | { | 
            ||
| 12 | /** コールバック関数 */  | 
            ||
| 13 | private $callback;  | 
            ||
| 14 | /** コンテキスト */  | 
            ||
| 15 | private $context;  | 
            ||
| 16 | /** キャッシュするかどうか */  | 
            ||
| 17 | private $cached;  | 
            ||
| 18 | /** コールバックの実行結果 */  | 
            ||
| 19 | private $value;  | 
            ||
| 20 | |||
| 21 | /**  | 
            ||
| 22 | * コンストラクタ  | 
            ||
| 23 | * @param callable $callback コールバック関数  | 
            ||
| 24 | * @param array $context コンテキスト  | 
            ||
| 25 | * @param boolean $cached キャッシュするかどうか  | 
            ||
| 26 | * @return void  | 
            ||
| 27 | */  | 
            ||
| 28 | public function __construct($callback, $context = [], $cached = true)  | 
            ||
| 29 |     { | 
            ||
| 30 | $this->callback = $callback;  | 
            ||
| 31 | $this->cached = $cached;  | 
            ||
| 32 | $this->context = $context;  | 
            ||
| 33 | }  | 
            ||
| 34 | |||
| 35 | /**  | 
            ||
| 36 | * 評価する  | 
            ||
| 37 | * @return mixed 実行結果  | 
            ||
| 38 | */  | 
            ||
| 39 | public function fetch()  | 
            ||
| 40 |     { | 
            ||
| 41 |         if ($this->cached && isset($this->value)) { | 
            ||
| 42 | return $this->value;  | 
            ||
| 43 | }  | 
            ||
| 44 | $args = $this->context;  | 
            ||
| 45 | // useで引数を指定した場合、call_user_func_arrayの$argsと  | 
            ||
| 46 | // 引数の数が合わなくなり警告が出るが問題なく実行出来る  | 
            ||
| 47 | $result = @call_user_func_array($this->callback, $args);  | 
            ||
| 48 |         if ($this->cached) { | 
            ||
| 49 | $this->value = $result;  | 
            ||
| 50 | }  | 
            ||
| 51 | |||
| 52 | return $result;  | 
            ||
| 53 | }  | 
            ||
| 54 | }  | 
            ||
| 55 |