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 | 12 | public function __construct($cache_config) { |
|
| 10 | |||
| 11 | public function save($filename, $objectChain, $templateChain) { |
||
| 46 | |||
| 47 | 6 | View Code Duplication | public function onTemplateSaved($id, $type, $name) { |
| 48 | 6 | $query = "template.value='$id:$type:$name' order by none"; |
|
| 49 | 6 | $objects = $this->cachestore->find("/", $query, 0, 0); |
|
| 50 | |||
| 51 | $template = function($object) { |
||
| 52 | return $object->data->filename; |
||
| 53 | 6 | }; |
|
| 54 | |||
| 55 | 6 | $result = $this->cachestore->call($template,array(),$objects); |
|
| 56 | 6 | $result = array_unique($result); |
|
| 57 | |||
| 58 | 6 | foreach ($result as $filename) { |
|
| 59 | $this->invalidate($filename); |
||
| 60 | 6 | } |
|
| 61 | 6 | } |
|
| 62 | |||
| 63 | 12 | View Code Duplication | public function onObjectSaved($id) { |
| 78 | |||
| 79 | 12 | public function invalidate($filename) { |
|
| 80 | 12 | global $store; |
|
| 81 | $absFilename = $store->get_config("files")."cache/".$filename; |
||
| 82 | $stamp = time(); |
||
| 83 | |||
| 84 | if (file_exists($absFilename)) { |
||
| 85 | if (filemtime($absFilename) > $stamp + 2) { // do not touch file which will expire soon |
||
| 86 | touch($absFilename, $stamp + 1); // set mtime to now; this means the cache image is now invalid; |
||
| 87 | } |
||
| 88 | } |
||
| 89 | } |
||
| 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: