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 | 36 | public function __construct($cache_config) { |
|
| 10 | |||
| 11 | 12 | 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 | 12 | } |
|
| 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 | 18 | View Code Duplication | public function onTemplateSaved($id, $type, $name) { |
| 48 | 18 | $query = "template.value='$id:$type:$name' order by none"; |
|
| 49 | 18 | $objects = $this->cachestore->find("/", $query, 0, 0); |
|
| 50 | |||
| 51 | $template = function($object) { |
||
| 52 | return $object->data->filename; |
||
| 53 | 18 | }; |
|
| 54 | |||
| 55 | 18 | $result = $this->cachestore->call($template,array(),$objects); |
|
| 56 | 18 | $result = array_unique($result); |
|
| 57 | |||
| 58 | 18 | foreach ($result as $filename) { |
|
| 59 | $this->invalidate($filename); |
||
| 60 | 18 | } |
|
| 61 | 18 | } |
|
| 62 | |||
| 63 | 36 | 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: