我认为,如果您将其分解为更小的步骤,您就可以实现 DRY 架构。我看到的步骤是:
- 创建客户端
- 创建用户
- 关联(通过数据透视表、连接表等)
- 电子邮件
为避免出现可怕的重复代码,您需要在一个或多个服务类中围绕这些代码创建一个方法。然后,您将创建一个操作,封装基于这些方法所涉及的所有步骤。
不要害怕在你的服务类之外实现一些东西——这并不意味着它在你的服务层之外。
我将注册客户兴趣视为一项操作。您遵循同步步骤来实现所需的操作。因此,基于创建用户、客户端等方法,我们可以构建一个操作来注册客户兴趣,如下所示:
<?php
class ClientService {
public function addAction(IAction $action)
{
return $action->process();
}
public function createUser() {} // business logic for creating a user.
public function createClient() {} // business logic for creating a client.
public function createAssociation() {} // business logic for creating an association.
}
interface IAction {
public function process();
}
class RegisterClientInterestAction implements IAction {
protected $client;
public function __construct(ClientService $client)
{
$this->client = $client;
}
public function process()
{
$this->createUser()->createClient()->createAssociation();
}
private function createUser() {} // interact with your client service to call the method $client->createUser()
private function createClient() {} // interact with your client service to call the method $client->createClient()
private function createAssociation() {} // interact with your client service to call the method $client->createAssociation()
}
//USAGE
$service = new ClientService;
$results = $service->addAction(new RegisterClientInterestAction($service));
?>
通过这种方式,您可以在新操作中使用 createUser 等方法,而无需复制代码。通过在服务类上添加 addAction,您仍在服务层内部执行业务逻辑。
如果需要两个或更多服务,我会采取稍微不同的方法,将execute 移动到该操作的位置。
就处理多个服务而言,您可以在操作的构造函数中使用 DI。
像这样:
<?php
class Service {
public function addAction(IAction $action)
{
return $action->process();
}
// Other stuff for a base service...
}
class UserService extends Service {
public function createUser() {} // business logic for creating a user.
}
class ClientService extends Service {
public function createClient() {} // business logic for creating a client.
public function createAssociation() {} // business logic for creating an association.
}
interface IAction {
public function process();
}
class RegisterClientInterestAction implements IAction {
protected $client;
protected $service;
public function __construct(ClientService $client, UserService $user)
{
$this->user = $user;
$this->client = $client;
}
public function process()
{
$this->createUser()->createClient()->createAssociation();
}
private function createUser() {} // interact with your user service to call the method $client->createUser()
private function createClient() {} // interact with your client service to call the method $client->createClient()
private function createAssociation() {} // interact with your client service to call the method $client->createAssociation()
}
//USAGE
$service = new Service;
$results = $service->addAction(new RegisterClientInterestAction(new ClientService, new UserService));
?>