vendredi 10 août 2018

Use Factory Pattern in Laravel

I am working on a Laravel project and want to implement Factory and Repository pattern in my project. However, I still don't know where should I use Factory pattern? It's still very confusing. I understand that it's not necessary to use the Factory pattern for every single project but as a part of my study, I want to learn more about the combination of this 2 patterns. This is my code example. Hope I can get help and explains from you guys. Thank you.

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();
   }
   .....
} 

Aucun commentaire:

Enregistrer un commentaire