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 |
||
5 | trait Language { |
||
6 | |||
7 | /** |
||
8 | * \addtogroup Localization Localization |
||
9 | * @{ |
||
10 | */ |
||
11 | |||
12 | /** \brief Store the language for a multi-language bot */ |
||
13 | public $language; |
||
14 | |||
15 | /** \brief Table contaning bot users data in the sql database. */ |
||
16 | public $user_table = '"User"'; |
||
17 | |||
18 | /** \brief Name of the column that represents the user id in the sql database */ |
||
19 | public $id_column = 'chat_id'; |
||
20 | |||
21 | /** |
||
22 | * \brief Get current user language from the database, and set it in $language. |
||
23 | * @param $default_language <i>Optional</i>. Default language to return in case of errors. |
||
24 | * @return Language set for the current user, $default_language on errors. |
||
|
|||
25 | */ |
||
26 | public function getLanguageDatabase($default_language = 'en') { |
||
75 | |||
76 | /** |
||
77 | * \brief Get current user language from redis, as a cache, and set it in language. |
||
78 | * \details Using redis database as cache, seeks the language in it, if there isn't |
||
79 | * then get the language from the sql database and store it (with default expiring of one day) in redis. |
||
80 | * It also change $language parameter of the bot to the language returned. |
||
81 | * @param $default_language <i>Optional</i>. Default language to return in case of errors. |
||
82 | * @param $expiring_time <i>Optional</i>. Set the expiring time for the language on redis each time it is took from the sql database. |
||
83 | * @return Language for the current user, $default_language on errors. |
||
84 | */ |
||
85 | public function getLanguageRedis($default_language = 'en', $expiring_time = '86400') : string { |
||
111 | |||
112 | /** |
||
113 | * \brief Set the current user language in both redis, sql database and $language. |
||
114 | * \details Save it on database first, then create the expiring key on redis. |
||
115 | * @param $language The new language to set. |
||
116 | * @param $expiring_time <i>Optional</i>. Time for the language key in redis to expire. |
||
117 | * @return On sucess, return true, throw exception otherwise. |
||
118 | */ |
||
119 | public function setLanguageRedis($language, $expiring_time = '86400') { |
||
151 | |||
152 | /** @} */ |
||
153 | |||
154 | } |
||
155 |
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.