在模型中解决这个问题的最佳方法是什么?
我经常遇到这种情况,并且一直很好奇是否有更好的方法。
考虑这一点(仅作为示例,假设有一个 OO 查询生成器)
class Dogs extends Pets {
public function getAll() {
return $this->parseRows($this->db->get('dogs'));
}
public function getBig() {
return $this->parseRows($this->db->get('dogs')->where('size', '>', 10));
}
public function getSmelly() {
return $this->parseRows($this->db->get('dogs')->where('smell', '=', 'bad'));
}
private function parseRows($rows) {
foreach($rows as &$row) {
$row['id'] = (int) $row['id'];
$row['categoryName'] = Categories::getById($row['categoryId']);
}
return $rows;
}
}
基本上,我需要使用大量数据库查询,但它们都需要经过后处理来将内容分配给它们。我一直在使用上面这样的模式。
这是执行此操作的最佳实践方法吗?
I come across this a lot, and have always been curious if there is better way.
Consider this (example only, assume an OO query builder)
class Dogs extends Pets {
public function getAll() {
return $this->parseRows($this->db->get('dogs'));
}
public function getBig() {
return $this->parseRows($this->db->get('dogs')->where('size', '>', 10));
}
public function getSmelly() {
return $this->parseRows($this->db->get('dogs')->where('smell', '=', 'bad'));
}
private function parseRows($rows) {
foreach($rows as &$row) {
$row['id'] = (int) $row['id'];
$row['categoryName'] = Categories::getById($row['categoryId']);
}
return $rows;
}
}
Basically, I need to use a lot of database queries, but they all need to go through a post-processing to assign things to them. I have been using a pattern like above.
Is this the best practice way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说,公共界面似乎不错。关于实现,有很多话要说,因为对象关系映射器是现代编程的基石之一(恕我直言)。
如果您想了解有关实现 ORM 的其他方法的更多信息,我建议您查看开源框架,例如 Doctrine 或 CakePHP 的 ORM。
关于私有实现,我想添加一个注释:如果 Category::getById 对数据库进行往返调用,这是低效的,因为一张包含许多狗的表会导致(至少)尽可能多的数据库调用,这是次优。这就是为什么像上面提到的那样的 ORM 允许开发人员指定关联(例如,狗有一个类别)并自动生成“LEFT JOIN”语句。
To me the public interface seems decent. Regarding the implementation, there is a lot to be said, as object-relational mappers are one of the cornerstones of modern programming IMHO.
If you would like to learn more about alternate ways of implementing ORM, I'd suggest looking at open-source frameworks such as Doctrine or CakePHP's ORM.
One note I'd like to add regarding the private implementation: if Categories::getById does a roundtrip call to the database, that is inefficient, as a table with many dogs would lead to (at least) as many db calls, which is suboptimal. This is why ORMs like the ones mentioned above allow the developer to specify associations (eg. a Dog has a Category) and automatically generate the "LEFT JOIN" statements.
与 Doctrine 相比,我更喜欢使用 Symfony 和 Propel 1.5。在 propel 1.5 中,您可以生成面向对象的查询,例如:
http://www.propelorm .org/wiki/Documentation/1.5/WhatsNew
祝你好运
I prefer using Symfony and Propel 1.5 over Doctrine. In propel 1.5, you can generate object oriented queries such as:
http://www.propelorm.org/wiki/Documentation/1.5/WhatsNew
Best of luck