2010-05-26 49 views
0

我爲客戶創建了一個基本類。訪問類中的數組集合的最佳實踐

我以前沒有這樣做,想知道訪問數據的最佳方式。

對於客戶數組中的每個字段,我是否應該有一個get()方法,或者我應該簡單地將客戶數組傳回並訪問該頁面。

即剛好返回數組

class Customer { 

    protected $id; 
    protected $customer; 

    public function __construct($customer_id) { 
    $this->id = $customer_id; 
    $this->set_customer(); 
    } 

    protected function set_customer() { 
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'"); 
    $this->customer = mysql_fetch_row($query); 
    } 

    public function get_customer() { 
    return $this->customer; 
    } 
} 

與陣列中創建的每個項目的方法

class Customer { 

    protected $id; 
    protected $customer; 

    public function __construct($customer_id) { 
    $this->id = $customer_id; 
    $this->set_customer(); 
    } 

    protected function set_customer() { 
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'"); 
    $this->customer = mysql_fetch_row($query); 
    } 

    public function get_customer_name() { 
    return $this->customer->customer_name; 
    } 

    ... 

    ... 
} 

與基於Tobias的反饋選項3:(如果不知道語法是正確的)

class Customer { 

    protected $id; 
    protected $customer; 

    public function __construct($customer_id) { 
    $this->id = $customer_id; 
    return $this->set_customer(); 
    } 

    protected function set_customer() { 
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'"); 
    return mysql_fetch_row($query); 
    } 
} 

回答

1

我會說最好只返回一個數組的所有數據,而不是僅僅爲每個字段創建邏輯。它可能會經常發生,你需要更多的一個領域,併爲此調用不同的方法會很煩人。

1

擁有一套功能默認情況下,返回的數據 - 沒有壞處做,如果你總是我們e之後的數據。

+0

托比亞斯,作爲一個新手,我可以通過改變以下幾行來達到你的建議嗎? 舊:$ this-> set_customer(); new:return $ this-> set_customer(); AND old:$ this-> customer = mysql_fetch_row($ query); new:return mysql_fetch_row($ query); – 2010-05-27 01:30:18

+0

是的,那應該工作:) – Tobias 2010-05-27 18:10:56

0

在我看來,後一種方法是更好的,你得到一個關於客戶的所有信息,從不同的是第一種方法,你只使用該行所有在你的項目中返回客戶行和那裏的類中得到客戶的詳細信息。

0

有get_和set_方法的好處是你可以讓這個類更聰明。使用類的視圖編碼器不能將變量設置爲無效值,因爲類知道有效值是什麼並且可以返回錯誤。您可以爲每個字段添加valid_方法,以允許視圖編碼器查看結果是否有效。您最終得到更好,更一致的數據。