2012-03-26 233 views
4

我想決定是否爲我的應用程序/數據庫中的每個內容類型創建許多類,或者只是使用過程代碼。對象集合類是否

版本1:

  • 爲每個對象集合類:

    class App{ 
    
        protected $user_collection; 
    
        function getUserCollection(){ 
        if(!isset($this->user_collection) 
         $this->user_collection = new UserCollection($this); 
    
        return $this->user_collection; 
        } 
    
        // ... 
    
    } 
    
    class UserCollection{ 
    
        function __construct(App $app){ 
        $this->app = $app; 
        } 
    
        function getUser($user){ 
        return new User($this->app, $user); 
        } 
    
        function getUsers($options){ 
        $users = $this->app->getDatabase()->query($options); 
        foreach($users as &$user) 
         $user = new User($this, $user);   
        return $users; 
        } 
    
        // ... 
    
    } 
    

這我使用類似:

$app = new App(); 
echo $app->getUserCollection()->getUser('admin')->email_address; 


版本2:

  • 保持所有方法在一個類

    class App{ 
    
        function getUsers($options){ 
        $users = $this->getDatabase()->query($options); 
        foreach($users as &$user) 
         $user = new User($this, $user);   
        return $users; 
        } 
    
        function getUser($user){ 
        return new User($this, $user); 
        } 
    
        // ... 
    
    } 
    

使用等:

$app = new App(); 
echo $app->getUser('admin')->email_address; 


3版本:

  • 使getUsers()一個靜態方法在 「用戶」 類(方法實例化一個新的用戶對象):

    $app = new App(); 
    echo User::getUser($app, 'admin')->email_address; 
    

我應該走哪條路? 「用戶」對象只是一個例子,App有其它物體太像「數據庫」,「頁」等

回答

1

Personnaly,所以經常使用的第二與一個方法是這樣的:

class user { 

    /** 
    * Load object from ... 
    */ 
    public function load($userId) {} 

    /** 
    * Insert or Update the current object 
    */ 
    public function save() {} 

    /** 
    * Delete the current object 
    */ 
    public function delete() { 
     // delete object 
     // Reset ID for a future save 
     $this->UserID = null; 
    } 

    /** 
    * Get a list of object 
    */ 
    public static function getList() { 
     // Make your search here (from DB) 
     // Put rows into new "SELF" object 
     $list = array(); 
     foreach($rows as $row) { 
      $obj = new self(); 
      $obj->populate($row); 

      $list[$obj->UserID] = $obj; // Associative array or not... 
     } 
    } 
} 

就像你看到的,我把我的「的GetList」功能,靜態簡單地訪問這樣的:

$listUsers = user::getList(); 

OK,這是很簡單,但簡單的應用程序的大多數情況下工作。

2

我會使用你的版本1,但我會讓App的getUser()和getUsers()方法。 這可以擺脫笨拙的getUserCollection()調用,因爲在getUser()中,而不是你只是調用$ this-> user_collection。

相關問題