简短回答
您无需费心创建两个映射器Author
and AuthorCollection
。如果你的程序不需要AuthorMapper
and an AuthorCollectionMapper
为了顺利工作并拥有干净的源,无论如何,做你最舒服的事情。
Note:选择这条路线意味着您应该格外小心SRP http://en.wikipedia.org/wiki/Single_responsibility_principle违规行为。
长(呃)答案
这完全取决于您想要做什么。为了这篇文章,让我们打电话AuthorMapper
项目数据映射器和AuthorCollectionMapper
集合数据映射器。
通常,项目映射器不会像其集合映射器那么复杂。项目映射器通常会only通过主键获取,从而限制结果,使映射器干净整洁,不受其他特定于集合的东西的影响。
One main part of these "collection-specific things" I bring up is conditions1 and how they're implemented into queries. Often within collection mappers you'll probably have more advanced, longer, and tedious queries than what would normally be inside an item data mapper. Though entirely possible to combine your average item data mapper query (SELECT ... WHERE id = :id
) with a complicated collection mapper query without using a smelly condition2, it gets more complicated and still bothers the database to execute a lengthy query when all it needed was a simple, generic one.
此外,尽管您指出,使用项目映射器我们实际上只能通过主键获取,但使用项目映射器处理其他事情通常会变得更加简单。项目映射器save()
and remove()
方法可以比尝试使用集合映射器来保存/删除项目更好地处理(使用正确的实现)作业。而且,除了这一点之外,很明显,有时在使用集合映射器的过程中save()
and remove()
方法,集合映射器可能想要利用项目映射器方法。
针对您下面的问题,您可能多次需要设置条件来从数据库中删除行集合。例如,您可能有一个垃圾邮件标志,设置后会隐藏帖子,但会在三十天内自毁。在这种情况下,您很可能有一个垃圾邮件标志条件和一个时间范围条件。另一种可能是在删除答案三十天后删除答案下的所有评论。我提到三十天是因为至少将这些数据保留一段时间是明智的,以防有人想要他们的评论,或者事实证明带有垃圾邮件标志的行实际上不是垃圾邮件。
1. Condition here means a property set on the collection instance which the collection mapper's query knows how to handle. If you haven't already, check out @tereško's https://stackoverflow.com/users/727208/teresko answer here https://stackoverflow.com/questions/11942842/who-should-handle-the-conditions-in-complex-queries-the-data-mapper-or-the-serv/11943107#11943107.
2. This condition is different and refers to the "evil if" https://stackoverflow.com/questions/1554180/why-is-the-if-statement-considered-evil people speak of. If you don't understand their nefariousness, I'd suggest watching some Clean Code Talks. This one http://www.youtube.com/watch?v=4F72VULWFvc specifically, but all are great.