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 |
||
21 | trait Language |
||
22 | { |
||
23 | |||
24 | /** |
||
25 | * \addtogroup Localization Localization |
||
26 | * @{ |
||
27 | */ |
||
28 | |||
29 | /** \brief Stores the language for a multi-language bot */ |
||
30 | public $language; |
||
31 | |||
32 | /** PDO connection to the database. */ |
||
33 | public $pdo; |
||
34 | |||
35 | /** \brief Table containing bot users data into database. */ |
||
36 | public $user_table = '"User"'; |
||
37 | |||
38 | /** \brief Name of the column that represents the user ID into database */ |
||
39 | public $id_column = 'chat_id'; |
||
40 | |||
41 | /** |
||
42 | * \brief Get current user's language from the database, and set it in $language. |
||
43 | * @param $default_language <i>Optional</i>. Default language to return in case of errors. |
||
44 | * @return Language set for the current user, $default_language on errors. |
||
|
|||
45 | */ |
||
46 | public function getLanguageDatabase($default_language = 'en') |
||
77 | |||
78 | /** |
||
79 | * \brief Get current user language from Redis (as a cache) and set it in language. |
||
80 | * \details Using Redis as cache, check for the language. On failure, get the language |
||
81 | * from the database and store it (with default expiring time of one day) in Redis. |
||
82 | * |
||
83 | * It also change $language parameter of the bot to the language returned. |
||
84 | * @param $default_language <i>Optional</i>. Default language to return in case of errors. |
||
85 | * @param $expiring_time <i>Optional</i>. Set the expiring time for the language on |
||
86 | * redis each time it is took from the sql database. |
||
87 | * @return Language for the current user, $default_language on errors. |
||
88 | */ |
||
89 | public function getLanguageRedis($default_language = 'en', $expiring_time = '86400') : string |
||
106 | |||
107 | /** |
||
108 | * \brief Set the current user language in both Redis, database and internally. |
||
109 | * \details Save it into database first, then create the expiring key on Redis. |
||
110 | * @param $language The language to set. |
||
111 | * @param $expiring_time <i>Optional</i>. Time for the language key in redis to expire. |
||
112 | * @return On sucess, return true, throws exception otherwise. |
||
113 | */ |
||
114 | public function setLanguageRedis($language, $expiring_time = '86400') |
||
140 | |||
141 | /** @} */ |
||
142 | } |
||
143 |
In PHP traits cannot be used for type-hinting as they do not define a well-defined structure. This is because any class that uses a trait can rename that trait’s methods.
If you would like to return an object that has a guaranteed set of methods, you could create a companion interface that lists these methods explicitly.