Keeping DAO and domain object separate

I've got a User domain object class, and a UserDAO class. The User only cares about it's state, and UserDAO only about the data storage. From what I've read, they should not know nor care about each other.

I then wondered how I could use my User class to do things with UserDAO and vice versa. After some research I found out about Service classes, that they're supposed to couple a bunch of related classes together for interaction User and UserDAO in my case).

If DAOs aren't supposed to know nor care about domain objects why have I seen some DAOs that accept their corresponding domain object as an argument or even return it?

class UserDAO
{
    //other logic

    public function fetchById($id)
    {
        //user fetch logic

        return new User(...);
    }

    public function persist(User $user)
    {
        //user persist logic
    }

    //other logic
}

What would be the correct way of handling this? With the above UserDAO is clearly aware of User.


There's a bit of a confusion here...

In DDD context the Reposity pattern fits better than DAO objects. You can check the difference between Repository and DAO here.

The repository do have knowledge about your domain objects, but your domain object do not know about repositories. The reason for this is separation of concerns and good layering.

Repositories is usually injected at some aplication level class. Example of aplication level classes are classes that process the user request like controllers(mvc contexts) or webservices.

Repositories can also be injected in Domain Service but Domain Services is normally used to resolve problems of significant business operation or for operations that do not belong to a unique entity in domain context.

链接地址: http://www.djcxy.com/p/56246.html

上一篇: 数据映射器模式和重复对象

下一篇: 保持DAO和域对象分离