【问题标题】:Use Factory Pattern in Laravel在 Laravel 中使用工厂模式
【发布时间】:2019-01-17 18:52:19
【问题描述】:

我正在开发一个 Laravel 项目,并希望在我的项目中实现工厂和存储库模式。但是,我仍然不知道应该在哪里使用工厂模式?它仍然非常混乱。我知道不必为每个项目都使用工厂模式,但作为我学习的一部分,我想了解更多关于这两种模式组合的信息。这是我的代码示例。希望我能得到你们的帮助和解释。谢谢你。

class ProductFactory 
{
    public function create()
    {
       return new Product; 
    }
}




class ProductRepository implements ProductRepositoryInterface
{
   protected $productFactory; 

   public function __contruct(
      ProductFactory $productFactory
   )
   {
      $this->productFactory = $productFactory      
   }
   public function all()
   {
      return Product::all();
   }
   public function loadById($id);
   {
      return Product::find($id);
   }
   public function save($data,$id=NULL)
   {
       if($id != NULL){
         $product = $this->loadById($id)
       }
       else{
         $product = $this->productFactory->create(); 
       }
       return $product->fill($data)->save();
   }
   .....
} 

【问题讨论】:

    标签: laravel design-patterns repository factory


    【解决方案1】:

    我认为您需要拆分工厂和存储库。例如:

    class ProductRepository implements ProductRepositoryInterface
    {
        protected $product; 
    
        public function __contruct(Product $product)
        {
            $this->product = $product;
        }
        //...
    }
    

    但对于存储库中的 DI 来说不是必需的,您的 all()、find() 等方法放在 AbstractRepository 中。您的产品存储库:

        class ProductRepository extends AbstractRepository implements ProductRepositoryInterface
        {
            public function __contruct()
            {
               //model property in AbstractRepository
                $this->model = new Product();
            }
        }
    

    如果你想为它写测试,你可以使用 laravel 容器: 应用服务提供者:

    $this->app->bind(Product::class, function ($app) {
        return new Product();
    });
    

    产品存储库:

    $this->model = app()->make(Product::class);
    

    PS:我认为工厂没用,在大多数情况下我使用容器。但在一些困难的情况下我使用工厂,例如:

    class ProductFactory
    {
         public static function create(int $type, array $attributes): ProductInterface
         {
              switch ($type) {
                   case 'market':
                     return new MarketProductModel($attributes);
                     break;
                   case 'shop':
                     $model = new ShopProductModel($attributes);
                     $model->setMathCoef(1.2);
    
                     return $model;
                     break;
                   case 'something':
                     return new SomethingProductModel($attributes);
                     break;
              }
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2015-02-01
      相关资源
      最近更新 更多