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 f开发者_开发知识库unction 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?
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.
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
精彩评论