我想決定是否爲我的應用程序/數據庫中的每個內容類型創建許多類,或者只是使用過程代碼。對象集合類是否
版本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有其它物體太像「數據庫」,「頁」等