2017-10-19 77 views
2

當從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 ... 
} 
+0

漂亮的意見爲基礎,但它會讓你的構造乾淨,讓你的抽象水合物抽象類或特性。 – Devon

+0

如果你有一個函數,那麼你也可以在構造好這個對象之後調用它,以防萬一需要。如果你用不同的輸入測試特定的功能而不創建一堆對象,這是有用的 – apokryfos

回答

1

當你有很多屬性類,每個屬性擁有它自己的二傳手與專項檢查,這是將他們全部稱爲一個有用的方式,而不是一個接一個。

它的第二個目的是如果你需要重新使用你的對象(比方說執行測試)與新的價值觀。你不必重建一個新的(或每個設置者),只需回顧水合物,你的班級屬性將被更新。

這是一個基本的例子:

<?php 
class Test 
{ 
    protected $titre; 
    protected $date; 
    protected ... 
    // And so on 

    public function __construct($value = array()) 
    { 
     if(!empty($value)) 
      $this->hydrate($value); 
    } 

    public function hydrate($data) 
    { 
     foreach ($data as $attribut => $value) { 
      $method = 'set'.str_replace(' ', '', ucwords(str_replace('_', ' ', $attribut))); 
      if (is_callable(array($this, $method))) { 
       $this->$method($value); 
      } 
     } 
    } 

    public function setTitle($title) 
    { 
     // Do specific check 
     $this->title = $title; 
    } 

    public function setDate($date) 
    { 
     // Do specific check 
     $this->date = $date; 
    } 
} 

$test = new Test(array("title" => "helloworld", ...)); 
// Manipulate the $test var and change stuff 
... 
$new_values = array("title" => "Hello, I am back", ...); 
$test->hydrate($new_values); 
?> 
+0

是的,我確定我得到了這個,但我想知道爲什麼我不應該直接把代碼放到構造函數中?只是爲了整潔的目的? – Will

+0

想象一下,你有很多屬性,你必須對它們執行自定義檢查,你的構造函數將會被無意識地填充,如果你需要改變這些值,你不能重新檢查它們。這種方式與水合功能,你保持一切乾淨整潔,你可以再次回憶水合功能的新值填充字段 – rak007

+0

我已更新我的問題,如果它可以幫助顯示我問 – Will