如何更改使用用于初始化模型的接口加载的模式存储库的使用? Laravel, 拉腊康
How to change the using of the pattern repository loaded using interfaces for initializing the model? Laravel, Laracom
美好的一天。
基于 https://github.com/Laracommerce/laracom 在 Laravel.
创建了一家商店
在这个过程中,我们注意到,在拉起接口实现的同时调用如下:
使用App\Products\Repositories\Interfaces\ProductRepositoryInterface;
其绑定声明在RepositoryServiceProvider (app\Providers\RepositoryServiceProvider.php),
直接调用使用App\Shop\Products\Repositories\ProductRepository使用;
(例如这里app/Shop/Orders/Repositories/OrderRepository。php)
你可以在代码中找到几个类似的例子,大多数情况下需要直接地址来调用
$repositoryWithModel = new Repository($modelObject).
我没有找到解决这种情况的明确方法,请教那些遇到质量实施示例的人的建议。
您的 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);
}
}
美好的一天。
基于 https://github.com/Laracommerce/laracom 在 Laravel.
创建了一家商店在这个过程中,我们注意到,在拉起接口实现的同时调用如下:
使用App\Products\Repositories\Interfaces\ProductRepositoryInterface;
其绑定声明在RepositoryServiceProvider (app\Providers\RepositoryServiceProvider.php),
直接调用使用App\Shop\Products\Repositories\ProductRepository使用;
(例如这里app/Shop/Orders/Repositories/OrderRepository。php)
你可以在代码中找到几个类似的例子,大多数情况下需要直接地址来调用 $repositoryWithModel = new Repository($modelObject).
我没有找到解决这种情况的明确方法,请教那些遇到质量实施示例的人的建议。
您的 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);
}
}