OOP、MVC - 模型和对象
我正在使用 CodeIgniter 构建一个网站,并且我有一个名为 Blog_model
的模型。
在 Blog_model
中,有一些方法可以提取特定主题的帖子列表,例如 getPopularPosts()
。
getPopularPosts()
在 posts 表中查询 topic_id
与指定帖子匹配的帖子列表,并按受欢迎程度对它们进行排序。因此,这是针对整个帖子表的一个查询(假设这最终会非常大),以查找具有 topic_id
x 的所有帖子。
然后,foreach
结果作为
一个单独的帖子 ID,它创建一个新的 Post
对象。 Post
类通过设置字段 id
来构造帖子。
要返回 Post
的内容,我分配 $post->getPost();
,它再次查询 posts 表以返回给定 的整行>id。
该组织(AFAIK)遵循良好的面向对象原则。但现在,对于每个帖子(再次假设数千、数百万,等等),我必须首先查询 id 列表,然后再次获取每个帖子的内容。如果我返回 30 个帖子,则意味着 31 个单独的查询。
或者,我可以打破面向对象的模式,并为 posts
中的每个帖子提取 *
,其中 topic_id
= x。然后,我有一个查询返回所有 30 个帖子,但现在我感觉不是那么面向对象。
该怎么办?
I'm building a site with CodeIgniter, and my I have a model called Blog_model
.
Within Blog_model
, there are methods to pull a list of posts for a specific topic, for example, getPopularPosts()
.
getPopularPosts()
queries the posts table for a list of posts with a topic_id
matching the one specified and sorts them by popularity. So, that's one query against the entire table of posts (let's assume this will be very large eventually) to find all posts with topic_id
x.
Then, foreach
result as
an individual post id, it creates a new Post
object. The Post
class constructs a post by setting the field id
.
To return the contents of a Post
, I assign $post->getPost();
, which queries the posts table again to return the entire row for the given id
.
This organization (AFAIK) follows a nice object oriented principle. But now, for every posts (again, let's assume thousands, millions, whatever...), I have to first query for a list of id
s and then again to get each post's content. If I'm returning 30 posts, that means 31 separate queries.
Alternatively, I could break the object oriented pattern and pull *
for each post in posts
where topic_id
= x. Then, I have one query that returns all 30 posts, but now I don't feel so object oriented.
What to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有理由有那么多疑问。您基本上只是在查找来自特定主题 ID 的 X 篇帖子...您应该将其作为一个对象返回,然后在 PHP 中迭代结果,因为一旦您达到拥有数百万行的要点
您应该像这样处理它:
然后您的控制器将如下所示:
以您当前设置的方式生成大量查询没有任何好处(实际上是一个大问题)上,vs 从查询生成一个对象并迭代控制器中的每一行并对数据执行任何您需要的操作。
There is no reason to have that many queries. You're basically just looking for X number of posts that are from a particular topic ID... you should return this as one object and then iterate through the result in PHP because it is significantly faster to do it that way once you get to the point of having millions of rows
You should go about it more like this:
Then your controller would look like this:
There is no benefit (and actually a big problem) with generating a ton of queries in the fashion that you currently have it set up, vs generating one object from the query and iterating through each of the rows in the controller and doing whatever you need with the data.