我的课程依赖于太多其他课程,我找不到改进它的方法。问题如下:
我有一个 ProductRepo、ProductFactory 和一个 ImageFactory 类。ProductRepo 对产品表执行 db 操作并将行作为数组获取。这个数组被传递给 ProductFactory 来创建一个 Product Modal。产品模式也有与之链接的图像。
客户端代码:
$products = $this->productRepo->findAll('...');
foreach($products as $product){
...
//get images
$images = $product->getImages();
...
}
Class ProductRepo implements ProductRepositoryInterface{
protected $productFactory;
protected $imageFactory;
public function __construct(ProductFactoryInterface $productFactory, ImageFactoryInterface $imageFactory)
{
$this->productFactory = $productFactory;
$this->imageFactory = $imageFactory;
}
public function findAll(...)
{
$result = $this->execute('....');
$products = $this->productFactory->make($result);
return $products;
}
public function getImages($productId)
{
$result = $this->execute('....');
$images = $this->imageFactory->make($result);
return $images;
}
}
Class ProductFactory implements ProductFactoryInterface{
protected $productRepo;
public function __construct(ProductRepositoryInterface $productRepo)
{
$this->productRepo = $productRepo;
}
public function make($items)
{
...
$products = [];
foreach($items as $item){
$product = new Product($item);
$item->setImages($this->productRepo->getImages($product->getId()));
$products[] = $product;
}
...
return $products;
}
}
Class ImageFactory implements ImageFactoryInterface{
public function make($items)
{
...
$images = [];
foreach($items as $item){
$image = new Image($item);
$images[] = $image;
}
...
return $images;
}
}
所以,我有以下问题:
循环依赖 ProductRepo --> ProductFactory --> ProductRepo
要跳过这个,我可以使用 setter 注入或使用代理模式。但我认为这不是一个好的解决方案。遇到这样的问题,大家是怎么处理的?
- ProductRepo 依赖于 ProductFactory 和 ImageFactory。依赖多个工厂是一种好习惯吗?
我认为问题很清楚。:) 谢谢