【问题标题】:Common dependencies in several Services多个服务中的常见依赖项
【发布时间】: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


    【解决方案1】:

    您对依赖注入有点误解。第一条规则是永远不要使用 new 关键字。

    如果你有如下的UserService.php,那么它会自动通过容器加载repositories。

    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
    

    【讨论】:

    • 感谢您的回答!但这并不能解决我的问题。我希望在我的服务实体中是相同的。
    • 请详细说明。如果您想使用容器,这就是这样做的方法:)
    • 哦,我第一次发问题时出错了。我已经更新了它。请检查一下。
    • 你写“我想实现这样的事情:”我的例子怎么不接近这个?
    • 如果您将使用具有相同依赖项的多个服务,则存储库中的实体将不同。请检查我添加的第一个代码附件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    相关资源
    最近更新 更多