我正在加载 Zend 1.11 并与 Doctrine 1.2 集成,并且已经阅读了很多关于使用服务层的内容。
据我了解,服务层位于业务逻辑之上,在控制器和域模型之间添加了一层。
但是,我被困在如何实际实现服务层上,主要是因为我有点不确定我应该为服务类定义什么类型的 API。
首先,给定一个服务类,App_Service_Memberships
它将处理业务实体组App_Model_Group
和用户App_Model_User
:
服务类的 API 是否应该通过接受或返回所述域模型的实例来公开类的组合?
或者服务类的 API 是否应该通过仅接受或返回诸如整数或数组之类的本机数据类型来隐藏类的组合?
比如说:
class App_Service_Memberships
{
public function addUserToGroup($user_id, $group_id)
{
//Create or retrieve domain models here and operate on them; handle persistence.
$membership = new App_Model_Membership();
$membership->member->user_id = $user_id;
$membership->group->group_id = $group_id;
$membership->join_date = date("Y-m-d H:i:s");
$membership->save();
return $membership->toArray();
}
public function getMembersOfGroup($group_id)
{
$groupMembers = array();
//Query objects here with Doctrine or the ORM of choice...
foreach($results as $membership){
$groupMembers[] = $membership->member->toArray();
}
return $groupMembers;
}
}
控制器只是将整数作为参数(来自表单的数据,或来自其他服务类的输出)传递给服务类,完全忽略了所涉及的域模型。
相对于:
class App_Service_Memberships
{
public function addUserToGroup(App_Model_UserInterface $user, App_Model_Group $group)
{
//Create or retrieve domain models here and operate on them; handle persistence.
$membership = new App_Model_Membership();
$membership->member = $user;
$membership->group = $group;
$membership->join_date = date("Y-m-d H:i:s");
$membership->save();
return $membership;
}
public function getMembersOfGroup(App_Model_Group $group)
{
$groupMembers = array();
//Query memberships here
foreach($results as $membership){
$groupMembers[] = $membership->member;
}
return $groupMembers;
}
}
控制器在哪里可以处理其范围内的域模型,并将它们传递给服务类?
您认为哪种做法更好?