Data Transfer Objects in PHP, lots of classes with the same contextual name

Well I just figured out that there's this DTO pattern. I wonder if they are useful.

I mean, should I map all my domain objects to their corresponding DTO objects and assign them to view instead to the domain objects themselves? I would, then, have a lot of classes with the same contextual name.

Like:

  • User(Domain Object),
  • UserDTO,
  • UserMapper or UserPersistenceFactory,
  • UserFactory,
  • UserSelectionFactory,
  • UserUpdateFactory,
  • UserAssembler(for DTO mapping),
  • UserCollection,
  • UserViewHelper(maybe)
  • etc...


    Typically a DTO can help you separate the data concerns of the database from the data concerns of the objects that make use of the data. You can place validation in the DTO to ensure that a particular member follows a specific format. In this way, that extra code doesn't clutter up the objects which don't care what the database needs.

    Additionally, DTO become powerful when talking to a database indirectly. However, this is of much more importance in languages that can auto-generate DTOs.

    Therein is the most powerful and compelling aspect of the DTO. That it can be auto-generated easily. This is also true in PHP, however it requires additional tools.

    I see why you might want to use them in PHP, however, I must admit I've yet to see a reason to do so myself. Typically a Factory + Object is enough for most applications.

    HOWEVER

    In an application that has objects that don't mirror the database directly, a DTO becomes empowered again. For example: an application that has People who are comprised of lots of meta information like Addresses and Personal Info and Credit Cards, could use DTOs for all the individual data, then use a Person object to handle all the usage of that data. In this way, a Transaction could be passed the Credit Card DTO directly, with no muss and no fuss. It could then access whatever data it needs to from the card. However, as soon as you want to put an Address on that Credit Card DTO, you no longer have a strict DTO.

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

    上一篇: 使用更多Cookie而不仅仅是会话哈希进行身份验证的原因?

    下一篇: PHP中的数据传输对象,许多具有相同上下文名称的类