【发布时间】:2020-11-01 02:00:16
【问题描述】:
我的目标是在不同的服务中拥有相同的依赖关系。
我需要它,因为在某些情况下,我将相同的实体用于不同的服务。示例:
...
$user = $this->userRepository->find(123);
$this->userService->doSomeWithUserRepository(); # here using $user entity
$this->commentService->doSomeWithUserRepository(); # and ! here too the same
...
这是我现在如何实现的示例:
public function __construct(
UserRepositoryInterface $userRepository,
FileRepositoryInterface $fileRepository,
CommentRepositoryInterface $commentRepository
) {
$this->userRepository = $userRepository;
$this->fileRepository = $fileRepository;
$this->commentRepository = $commentRepository;
$this->userService = new UserService(
$userRepository, $fileRepository, $commentRepository
);
$this->commentService = new CommentService(
$userRepository, $fileRepository, $commentRepository
);
$this->middleware(...
...
}
因此,正如您所见,使用这种方法,如果每个服务都有很多依赖项,构造函数可能真的又大又丑。
我想实现这样的目标:
public function __construct(
UserRepositoryInterface $userRepository,
FileRepositoryInterface $fileRepository,
CommentRepositoryInterface $commentRepository
UserService $userService,
CommentService $commentService
) {
$this->userRepository = $userRepository;
$this->fileRepository = $fileRepository;
$this->commentRepository = $commentRepository;
$this->userService = $userService;
$this->commentService = $commentService;
$this->middleware(...
...
}
我很高兴听到任何帮助/提示/评论。 也许我使用了错误的逻辑或什么?
谢谢
【问题讨论】:
标签: php laravel dependency-injection repository-pattern service-layer