我有用户和组。每个用户可以有任意数量的组。我想以分页形式显示用户组,一次 n 个组。我知道如何实现一个普通的分页,但是我不知道如何将它集成到我的领域驱动设计中(并且不会导致以后的代码重复)。我希望它像这样工作:
$adapter = new DatabaseAdapter(...);
$userRepository = new UserRepository($adapter);
$user = $userRepository->fetchById(1);
$groups = $user->getGroups()->getRange($offset, $limit);
对于其他域实体也是如此:
$projects = $user->getProjects()->getRange($offset, $limit);
...
简化后,我的代码如下所示:
class Group
{
private $_id;
private $_name;
public function __construct($id, $name) {
$this->setId($id);
$this->setName($name);
}
public function setId() {
$this->_id = $id;
}
public function getId() {
return $this->_id;
}
public function setName($name) {
$this->_name = $name
}
public function getName() {
return $this->_name;
}
}
class Groups
{
private $_elements = array();
public function __construct(array $groups) {
foreach($groups as $group) {
if(!($group instanceof Group)) {
throw new Exception();
}
$this->_elements[] = $group;
}
}
public function toArray() {
return $this->_elements;
}
}
class GroupMapper
{
private $_adapter;
public function __construct(DatabaseAdapterInterface $adapter) {
$this->_adapter = adapter;
}
public function fetchById($id) {
$row = $this->_adapter->select(...)->fetch();
return $this->createEntity($row);
}
public function fetchAll() {
$rows = $this->_adapter->select(...)->fetchAll();
return $this->createEntityCollection($rows);
}
private function createEntityCollection(array $rows) {
$collection = array();
foreach($rows as $row) {
$collection[] = $this->createEntity($row);
}
return $collection;
}
private function createEntity(array $row) {
return new Group($row['id'], $row['name']);
}
}
class User
{
private $_id;
private $_name;
private $_groups;
public function getId() {
return $this->_id;
}
public function setName($name) {
$this->_name = $name;
}
public function getName() {
return $this->_name;
}
public function setGroups($groups) {
$this->_groups = $groups;
}
public function getGroups() {
return $this->_grous;
}
}
class UserRepository
{
private $_userMapper = null;
private $_groupMapper = null;
public function __construct(DatabaseAdapterInterface $adapter) {
$this->_groupMapper = new GroupMapper($adapter);
$this->_userMapper = new UserMapper($adapter);
}
public function fetchById($id) {
$user = $this->_userMapper->fetchById($id);
if($user) {
$groups = $this->_groupMapper->fetchAllByUser($id);
$user->setGroups($groups);
}
}
public function fetchAll() {
...
}
}
谢谢您的帮助!