简体   繁体   中英

Pagination and OOP

Some may say that this problem is more about semantics but I guess it doesn't matter anyway.

I'm not very good with explanations so let me get straigth to the example, here're the classes

class User {
    public $id;
    public $name;
    function __construct($id, $name){
        $this->id = $id;
        $this->name = $name;
    }
}

class Group {
    public $id;
    public $name;
    public $members;
    function __construct($id, $name){
        $this->id = $id;
        $this->name = $name;
    }

    function getMembers(){
        if(empty($this->members)){
            foreach(getMembersFromDataBase($this->id) as $member){
                $this->members[] = new User($member['id'], $member['name']);
            }
        }
        return $this->members;
    }
}

Very self-explanatory. The problem is, $group->members looks like it's supposed to hold all members of that group, however if the group has about 10000+ members, this may take up some space, with every member having their unique data like names, ids, about me's and such. And to take it one step further it is unspeakable for a browser to display that many results at once, or even at all. How can pagination be done in this scenario? If I pass getMembers() a variable then $group->members becomes kind of nonsense because it is going to hold a very small portion of the group's members and what good is that?

Also this goes not for just this example, what ever it may be, groups, news, feeds - everything that may return too many rows at once, how is it done in OOP?

Its hard to imagine therefore when you would actually use getMembers() , unless it was for some internal operation like, what? Update subscriptions?

Well you might say that could be evoking a filter.

getMembersOwingSubscriptions($date);

You need to define what kind of filters you need to display to the users who will be looking at results in a browser.

getGroupMembersByRegion($region);
getGroupMembersPaged($start, $end);

These could then clearly map to their own sql statements, unless you foresee your classes doing computations that you cannot do in sql alone.

These might even be coming from specialized classes, perhaps then you find you have no use for getMembers();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM