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 |
||
| 2 | class cache { |
||
| 3 | 48 | public function __construct($cache_config) { |
|
| 10 | |||
| 11 | public function save($filename, $objectChain, $templateChain) { |
||
| 12 | if (!is_array($objectChain)) { |
||
| 13 | return false; |
||
| 14 | } |
||
| 15 | if (!is_array($templateChain)) { |
||
| 16 | return false; |
||
| 17 | } |
||
| 18 | if ( !$this->cachestore->exists('/') ) { |
||
| 19 | $this->cachestore->save( '/', 'pobject', new object ); |
||
| 20 | } |
||
| 21 | |||
| 22 | $data = new object; |
||
| 23 | $data->filename = $filename; |
||
| 24 | $data->objectChain = $objectChain; |
||
| 25 | $data->templateChain = $templateChain; |
||
| 26 | |||
| 27 | $properties = array(); |
||
| 28 | $properties["objectref"] = array(); |
||
| 29 | $properties["template"] = array(); |
||
| 30 | |||
| 31 | foreach ($objectChain as $id => $value) { |
||
| 32 | $properties["objectref"][] = array("name" => "id", "value" => $id); |
||
| 33 | } |
||
| 34 | foreach ($templateChain as $id => $template) { |
||
| 35 | foreach ($template as $name => $value) { |
||
| 36 | foreach ($value as $type => $dummy) { |
||
| 37 | $properties["template"][] = array("name" => "name", "value" => $id . ":" . $type . ":" . $name); |
||
| 38 | } |
||
| 39 | } |
||
| 40 | } |
||
| 41 | |||
| 42 | $this->cachestore->save("/" . md5($filename) . "/", "pcache", $data, $properties); |
||
| 43 | |||
| 44 | // $onsave = $this->onTemplateSaved("1944", "ppage", "ppage.view.div1.html.any"); |
||
| 45 | } |
||
| 46 | |||
| 47 | 24 | View Code Duplication | public function onTemplateSaved($id, $type, $name) { |
| 62 | |||
| 63 | 48 | View Code Duplication | public function onObjectSaved($id) { |
| 78 | |||
| 79 | 12 | public function invalidate($filename) { |
|
| 90 | |||
| 91 | public function delete($filename) { |
||
| 94 | } |
||
| 95 | ?> |
||
| 96 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: