1

我需要有经验的开发人员对此提出建议。让我直接进入它。

我有用户发布文章,我需要显示文章列表并显示发布它们的用户。

在我目前的程序方法中,它是这样的:

$result = mysql_getresult("SELECT users.*, articles.* 
                          FROM users JOIN articles ON users.id = articles.user_id
                          WHERE 1");
while($row = mysql_getrow($result)) {
    display_username($row);
    display_articletitle($row);
}

现在我想做OO方法

class User {
    protected $data;

    public function loadUserData($id) { $this->data = mysql_readstuff() }
    public function displayUserName() { echo $this->data['name'] }
}


class Article {
    protected $data;

    public function loadArticleData($id) { $this->data = mysql_readstuff() }
    public function displayArticleTitle() { echo $this->data['title'] }
}

OO的问题:

1.) 这些类有自己的方法来加载自己的数据(以及许多其他方法),因此使用 JOIN 一次获取所有数据的快速 mysql 查询在这里并不真正起作用。加载他们自己的数据对于许多其他方法(例如身份验证)非常有用。

2.) 我想分开展示(使用 savant3 模板)所以我应该把显示方法放在哪里?我将需要显示很多东西(工作、评论等),而且我认为在模板中为它们中的每一个都创建一个方法不是一个好主意。

该示例包含用户和文章,但我将有用户 + 评论、用户 + 工作 + 要求。

我想将显示方法设为静态并让它们带一个参数,但它与程序方法没有什么不同。或者创建一个 setData($row) 方法,将 $data 设置为它获得的参数。

对于这个问题,可能有一个通用的解决方案。

任何建议表示赞赏。

谢谢你,斯卡塞尔

4

2 回答 2

1

Article 类不应具有加载方法或显示方法。

我的建议是创建一个表网关

Class ArticleGateway {

    getArticles(){} // returns an array of article objects
    getArticlesByAuthor( Author $author ) {}

}

$articleGateway = new ArticleGateway() {}
$articles = $articleGateway->getArticles();

现在$articles包含一个文章对象数组。您可以在视图中对其进行迭代并显示文章。

于 2011-05-25T22:13:28.603 回答
0

Exactly as @galen said,

Dont let your class methods print out your data, let them return an array of the data, then you handle them as you need to view them:

I experiences this when developing my application. i can use my methods to load an android app data as well as a website application

于 2012-06-30T20:19:32.277 回答