加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 对象集合类与否

发布时间:2020-12-13 16:44:18 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试决定是否为我的应用程序/数据库中的每种内容类型创建许多类,或者只是坚持使用过程代码. 版本1: 为每个对象集合创建一个类: class App{ protected $user_collection; function getUserCollection(){ if(!isset($this-user_collection) $this-user
我正在尝试决定是否为我的应用程序/数据库中的每种内容类型创建许多类,或者只是坚持使用过程代码.

版本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;

我该走哪条路? “用户”对象只是一个例子,App也有其他对象,如“数据库”,“页面”等.

解决方法

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();

好的,它非常简单,但在大多数情况下工作简单的应用程序.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读