1 | <?php |
||
25 | trait UserUsernameTrait |
||
26 | { |
||
27 | public $usernameClass = false; |
||
28 | |||
29 | /** |
||
30 | * Check whether this user enables the username feature or not. |
||
31 | * @return boolean |
||
32 | */ |
||
33 | 4 | public function hasEnabledUsername() |
|
34 | { |
||
35 | 4 | if ($this->usernameClass === false || !is_string($this->usernameClass) || !class_exists($this->usernameClass)) { |
|
36 | return false; |
||
37 | } |
||
38 | 4 | return true; |
|
39 | } |
||
40 | |||
41 | /** |
||
42 | * Get username. |
||
43 | * This method may return null, please consider processing the abnormal conditions. |
||
44 | * @return BaseBlameableQuery |
||
45 | */ |
||
46 | 4 | public function getUsername() |
|
56 | |||
57 | /** |
||
58 | * Create or get username. |
||
59 | * @param $username |
||
60 | * @return null|Username |
||
61 | */ |
||
62 | 4 | public function createUsername($username) |
|
63 | { |
||
64 | 4 | if (!$this->hasEnabledUsername()) { |
|
65 | return null; |
||
66 | } |
||
67 | 4 | $usernameClass = $this->usernameClass; |
|
68 | 4 | $model = $usernameClass::findOne($this->getGUID()); |
|
69 | 4 | if (!$model) { |
|
70 | 4 | $model = $this->create($usernameClass); |
|
71 | 4 | $model->setGUID($this->getGUID()); |
|
72 | } |
||
73 | 4 | $model->content = $username; |
|
74 | 4 | return $model; |
|
75 | } |
||
76 | |||
77 | /** |
||
78 | * Set username. |
||
79 | * @param string|Username $username |
||
80 | * @return bool |
||
81 | */ |
||
82 | 2 | public function setUsername($username = null) |
|
93 | |||
94 | /** |
||
95 | * Remove username. |
||
96 | * @return bool |
||
97 | */ |
||
98 | 1 | public function removeUsername() |
|
102 | } |
||
103 |
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: