I want to refactor my Controller code which is creating a new record at table products
:
public function store(Request $request)
{
$newPro = Product::create([
'name' => $request->product_name,
'en_name' => $request->product_name_english,
'type' => $request->product_type,
'cat_id' => $request->category_product,
]);
...
}
Now in order to refactor this code, I have two options:
1- Create a separate method at the same Controller and then call it like this:
$newPro = self::createProduct($request->product_name,$request->product_name_english,$request->product_type,$request->category_product)
2- Create a separate Class and call it by the interface
or facade
(Best way)
Now I wanted to use the 2nd option but I don't know really how to!
So if you know please let me know...
CodePudding user response:
First create your repository service provider:
php artisan make:provider RepositoryServiceProvider
then you should map Interface and your Repository (ofcourse you must create ProductRepository and ProductRepositoryInterface too) inside register method like:
/**
* Register services.
*
* @return void
*/
public function register()
{
$this->app->bind(ProductRepositoryInterface::class, ProductRepository::class);
}
after that you can inject your repository to your controller like:
public function store(Request $request, ProductRepositoryInterface $productRepository)
{
$newPro = $productRepository->createProduct($productData);
...
}
Here is your ProductRepository:
<?php
namespace App\Repositories;
class ProductRepository extends BaseRepository implements ProductRepositoryInterface
{
protected Product $product;
/**
* @param Product $product
*/
public function __construct(Product $product)
{
$this->product = $product;
}
/**
* @param array $productArray
* @return Product
*/
public function createProduct(array $productArray): Product
{
return $this->product->create($productArray);
}
}
and your ProductRepositoryInterface:
<?php
namespace App\Repositories;
interface CategoryRepositoryInterface
{
/**
* @param array $productArray
* @return Product
*/
public function createProduct(array $productArray): Product;
}