2012-01-17 21 views
1

請看看這個課程,我知道應用程序之外的一段代碼幾乎沒有告訴我應該做什麼,但我想你明白基本上應該做什麼和被用於什麼。PHP - 從數據庫加載/刪除使用靜態方法或不?

<?php 

class Customer 
{ 
    const DB_TABLE = 'customers'; 

    public $id = NULL; 
    //all other properties here 

    function __construct($associative_array = NULL) 
    { 
     //fills object properties using values provided by associative array 
    } 

    static function load($customer_id) 
    { 
     $obj = new static(); //PHP 5.3 we use static just in case someone in future wants to overide this in an inherited class 

     //here we would load data from DB_TABLE and fill the $obj 

     return $obj; 
    } 

    static function delete($customer_id) 
    { 
     //here we just delete the row in the DB_TABLE based on $customer_id (which is the primary key of the table) 
    } 

    function save() 
    { 
     //saves $this properties into a row of DB_TABLE by either updating existing or inserting new one 
    } 
} 

而且任何類型的評論,你會做的代碼(即總是讚賞),這裏的主要問題是:「已經對SO大約讀了很多周圍多麼糟糕static方法和使用static一般情況下,在這段代碼中你會不會使兩種方法load/delete不是靜態的?如果是的話,你可以用一個小例子來解釋一下。「

這似乎很奇怪我沒有讓他們static,因爲我認爲這是奇怪,以創建從數據庫加載一個新的對象被迫每次寫:簡單地做

$obj = new Customer(); //creating empty object 
$obj->load(67); //loading customer with id = 67 

代替

$obj = Customer::load(67); //creates a new customer and loads data form DB 

回答

2

這一切都取決於你希望你如何編碼結構。只要你正確地使用它們,IMO的靜態功能並不壞。

例如,我的所有機型的功能都差不多,按照這個結構:

class models_car { 
    public static function getCar($id); 
    public static function getCars(); 
    public static function getCarsByDriver(models_driver $driver); 
    public function save(); 
    public function delete(); 
    public function isNew(); 
    public function getProperty1(); 
    public function getProperty2(); 
    public function getProperty3(); 
    public function setProperty1($value); 
    public function setProperty2($value); 
    public function setProperty3($value); 
} 

所以在這裏,你可以使用模型作爲特定條目的表示,如果你調用刪除或儲存,它是在對象本身的上下文中調用的。如果您調用getCar,getCars或getCarsByDriver,它們是靜態的,因爲它們不屬於特定對象,它們是返回填充對象的加載器。

儘管如此,這並不意味着它是最好的方法,但它是我多年來一直使用的方法,並且已被證明可以創建非常好且易於管理的代碼。

+0

讓我們來談談刪除,你沒有聲明'static'。如果使用你的代碼,我該怎麼做:'$ obj = getCar(78); $ obj-> delete();'我想這會在數據庫中刪除'id = 78'的行,但是刪除後'$ obj'中有什麼?例如:如果在刪除後我會調用'$ obj-> save();' – 2012-01-18 17:46:20

+1

@MarcoDemaio,我通常在我的對象中有一個RESET函數,並且在LOAD/DELETE上調用reset。因此,該對象變成了一個全新的實例。就像我說的,這不一定是最好的方式,但我喜歡它 – 2012-01-18 18:06:39