當從SQL數據庫實例化對象時,我讀到應使用hydrate()
函數直接填充我的對象而不是構造函數。PHP中的水合物和構造函數
以下代碼是否存在差異?
隨着水合物():
class User {
// attributes ...
public function __construct(array $data = array()) {
if (!empty($data)) {
$this->hydrate($data);
}
}
public function hydrate(array $data) {
foreach ($data as $key => $value) {
// One gets the setter's name matching the attribute.
$method = 'set'.ucfirst($key);
// If the matching setter exists
if (method_exists($this, $method)) {
// One calls the setter.
$this->$method($value);
}
}
}
// Getters/Setters and methods ...
}
進入直接構造:
class User {
// attributes ...
public function __construct(array $data = array()) {
if (!empty($data)) {
foreach ($data as $key => $value) {
// One gets the setter's name matching the attribute.
$method = 'set'.ucfirst($key);
// If the matching setter exists
if (method_exists($this, $method)) {
// One calls the setter.
$this->$method($value);
}
}
}
}
// Getters/Setters and methods ...
}
漂亮的意見爲基礎,但它會讓你的構造乾淨,讓你的抽象水合物抽象類或特性。 – Devon
如果你有一個函數,那麼你也可以在構造好這個對象之後調用它,以防萬一需要。如果你用不同的輸入測試特定的功能而不創建一堆對象,這是有用的 – apokryfos