开发者

Using a DAO within another DAO - good or bad practice?

开发者 https://www.devze.com 2022-12-17 00:01 出处:网络
This might be something very trivial, but I am a novice with some Object-Oriented patterns. Put simply, is it a bad practice to use methods from one DAO in another DAO? I am trying to create an entit

This might be something very trivial, but I am a novice with some Object-Oriented patterns.

Put simply, is it a bad practice to use methods from one DAO in another DAO? I am trying to create an entity within a DAO and find it very hard to create that entity using just that DAO. So, is it ok to use other DAO methods within the other DAO?

Example:

public function readAllUsers() {
    $sql = "SELECT * FROM user";
    return $this->execute($sql);
}

public function execute($sql) {
$result = mysql_query($sql, $this->getDBConnection())
                or die(mysql_error());
    $user = array();
    if(mysql_num_rows($result) > 0) {
        for($i = 0; $i < mysql_num_rows($result); $i++) {
            $row = mysql_fetch_assoc($result);
            $user[$i]->setUsername(row["userName"]);
             ...set user info...
            $user[$i]->setAddresses($addressDAO->readAddressByUserId($userId));
        }
    }
    return $user;
}

NOTE: There are a good bit of attributes like this in the user entity that have a one-to-many relationship with the entity itself (addresses, emails, phone numbers, etc.). The开发者_开发技巧 query that would be needed (with all the linking tables that are used) would be tremendously complex.

Thanks,

Steve


No, I wouldn't do it that way at all.

Sounds like you want to model a one-to-many relationship, so your hope is to use the inner DAO to get the many objects and then map them into the one.

Resist that temptation.

Your code tells you why:

  1. The outer loop brings back N objects with a one-to-many relationship.
  2. The inner loop queries once for each of the N objects and brings back its dependencies.

Classic noob N+1 query error. The network latency will kill you for large N.

The right thing to do is to do one query that brings back all your data at once and map it into the object(s) in question.

Maybe an ORM tool like Hibernate would be a good fit. If you have lots of 1:m relationships, I'd bet Hibernate would do as good as or a better job of generating efficient SQL than you will.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号