tags:

views:

50

answers:

2

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?

+2  A: 

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.

Flavius Stef
Thanks for your answer. You can assume the static method queries once and then holds the result in a static variable :). Basically, what I wanted to know if running all my results through the same function was optimal, in terms of a design issue.
alex
A: 

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

Homer6