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 |
||
| 3 | class _FileCache { |
||
| 4 | // Create a new FileCache instance. |
||
| 5 | // Parameters: |
||
| 6 | // $path: The path to the base directory which will be used for the cache. |
||
| 7 | // $expirationTimeInSeconds: The expiration time, in seconds, for items added to the |
||
| 8 | // cache. Any value less than 1 is automatically clamped to 1. |
||
| 9 | // Optional. Defaults to 30. |
||
| 10 | // $cleanInterval: How often to clean expired entries. On average, expired entries will |
||
| 11 | // be cleaned every $cleanInterval get or set requests. Any value < 1 will be clamped |
||
| 12 | // to 1. |
||
| 13 | // Optional. Defaults to 1000. |
||
| 14 | // $directoryDepth: The number of directories deep to make the cache. The directory names |
||
| 15 | // are derived from segments of the sha1 hash of the cache key, working from left to right. |
||
| 16 | // Each segment consists of the next two hexadecimal characters of the sha1 hash of the |
||
| 17 | // cache key. This must be between 1 and 10, inclusive. |
||
| 18 | // Optional. Defaults to 2. |
||
| 19 | public function __construct( |
||
| 36 | |||
| 37 | // Get an object from the cache. |
||
| 38 | // Parameters: |
||
| 39 | // $key: The cache key. |
||
| 40 | // Returns: |
||
| 41 | // The object which was previously stored, or false if a cache miss occurred. |
||
| 42 | public function get($key) { |
||
| 57 | |||
| 58 | // Store an object into the cache. |
||
| 59 | // Parameters: |
||
| 60 | // $key: The cache key. |
||
| 61 | // $value: The object to store. |
||
| 62 | public function set($key, $value) { |
||
| 70 | |||
| 71 | // Delete an object from the cache. |
||
| 72 | // Parameters: |
||
| 73 | // $key: The cache key. |
||
| 74 | public function delete($key) { |
||
| 88 | |||
| 89 | // Clean expired entries. |
||
| 90 | public function clean() { |
||
| 93 | |||
| 94 | // Clean expired entries from a directory. |
||
| 95 | public function cleanPath($path) { |
||
| 108 | |||
| 109 | private function getCacheFilename($key, $autoCreateDirectory = false) { |
||
| 119 | |||
| 120 | public function fixPermissions($user) { |
||
| 124 | |||
| 125 | |||
| 126 | } |
||
| 127 |
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: