如何更改使用接口初始化模型加载的模式存储库的使用? Larara,Laracom

问题描述 投票:1回答:1

早安。

基于Laravel上的https://github.com/Laracommerce/laracom创建了商店。

在此过程中,我们注意到,并通过如下调用调出了接口的实现:

使用App \ Products \ Repositories \ Interfaces \ ProductRepositoryInterface;

其绑定在RepositoryServiceProvider(app \ Providers \ RepositoryServiceProvider.php)中声明,

类似直接调用 使用App \ Shop \ Products \ Repositories \ ProductRepository 已使用;

(例如,此处app / Shop / Orders / Repositories / OrderRepository.php

您可以在代码中找到几个类似的示例,并且通常需要直接地址才能调用[$ repositoryWithModel =新的存储库($ modelObject)。

我没有找到解决此问题的明确方法,我请那些遇到过质量实施示例的人提供建议。

laravel oop design-patterns laravel-5.7
1个回答
0
投票

ProductRepository的实现期望将Product作为构造函数参数。存储库不应该这样做。相反,如果存储库必须处理产品模型,则应将其作为参数传递给函数。

例如,此:

    /**
     * @param Brand $brand
     */
    public function saveBrand(Brand $brand)
    {
        $this->model->brand()->associate($brand);
    }

可以重写为:

    /**
     * @param Product $product
     * @param Brand $brand
     */
    public function saveBrand(Product $product, Brand $brand)
    {
        $product->brand()->associate($brand);
    }

如果从构造函数中删除Product参数,则可以使用存储库而无需每次都使用new关键字创建存储库:

class BrandController extends Controller {

   public function __construct(ProductRepositoryInterface $repository) {
       $this->repository = $repository;
   }

   public function linkBrandToProduct(Request $request): void {
      $product = $this->repository->findProductById($request->productId);
      $brand = $this->repository->findBrandById($request->brandId);

      $this->repository->saveBrand($product, $brand);
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.