我有一个关于集合的数据映射器模式的问题。我一直在关注这篇关于存储库、集合和数据映射器模式的文章,我发现它非常有用,但我需要澄清一些事情:
在这些示例中,UserMapper 在其构造函数中采用了 UserCollection,这意味着 UserMapper 实际上负责获取从查询中返回的数据,并从该数据中构建一个集合。
这不会稍微违反 SRP 吗?DataMapper 不应该只从查询中返回一个原始数组,而不是构建并返回该数据的集合包装器吗?以代码为例,以下哪个更合适?:
$userCollection = new UserCollection;
$userMapper = new UserMapper;
$userCollection->addUsers( $userMapper->fetchAll() ); // where addUsers() takes an array and does what it needs to
VS
$userMapper = new UserMapper( new UserCollection );
$userCollection = $userMapper->fetchAll() // where fetchAll() queries the DB, then builds and returns a collection
第一个比较麻烦一些,但不是更松耦合吗?