Php 几种服务中的公共依赖关系
我的目标是在不同的服务中具有相同的依赖关系 我需要它,因为在某些情况下,我对不同的服务使用相同的实体。例如:Php 几种服务中的公共依赖关系,php,laravel,dependency-injection,repository-pattern,service-layer,Php,Laravel,Dependency Injection,Repository Pattern,Service Layer,我的目标是在不同的服务中具有相同的依赖关系 我需要它,因为在某些情况下,我对不同的服务使用相同的实体。例如: ... $user = $this->userRepository->find(123); $this->userService->doSomeWithUserRepository(); # here using $user entity $this->commentService->doSomeWithUserRepository(); # and
...
$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(...
...
}
我很高兴听到任何帮助/提示/评论。
也许我使用了错误的逻辑或其他什么
谢谢你你有点误解了。第一条规则是永远不要使用
new
关键字
如果您的UserService.php如下所示,那么它将通过容器自动加载存储库
class UserService
{
public function __construct(UserRepository $userRepository, FileRepository $fileRepository, CommentRepository $commentRepository)
{
...
}
}
因此,你可以做如下事情。此代码将解析UserService
,因为所有存储库都在构造函数中,所以它也将解析它们
public function __construct(UserService $userService) {
...
}
如果出于任何原因,希望在没有构造函数的情况下使用相同的依赖项注入功能,则可以使用app()
或resolve()
resolve(UserService::class); // will resolve user service with it 3 repositories
谢谢你的回答!但这并不能解决我的问题。我希望我的服务实体是相同的。请详细说明。如果你想使用容器,这就是方法:)哦,我在第一次发布问题时犯了错误。我已经更新了。请检查它。你写“我想实现这样的目标:”我的例子怎么不接近这个呢?如果你要使用具有相同依赖关系的多个服务,那么存储库中的实体就不一样了。请检查我添加的第一个代码附件。