我正在尝试决定是否为我的应用程序/数据库中的每种内容类型创建许多类,或者只是坚持使用过程代码.
版本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()成为“User”类中的静态方法(该方法实例化一个新的User对象):
$app = new App(); echo User::getUser($app,'admin')->email_address;
解决方法
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”函数设置为static,只需像这样访问:
$listUsers = user::getList();
好的,它非常简单,但在大多数情况下工作简单的应用程序.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。