我想重构我的控制器代码,这将在表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,
       ]);
       ...
     }

现在,为了重构这段代码,我有两个 Select :

1-在同一控制器上创建一个单独的方法,然后像这样调用它:

$newPro = self::createProduct($request->product_name,$request->product_name_english,$request->product_type,$request->category_product)

2-创建一个单独的类,按interfacefacade(最佳方式)调用它

现在我想使用第二个选项,但我真的不知道如何使用!

所以如果你知道请告诉我...

推荐答案

首先创建存储库服务Provider :

php artisan make:provider RepositoryServiceProvider

然后,您应该在register方法中映射接口和存储库(当然,您还必须创建ProductRepository和ProductRepositoryInterface),如:

/**
 * Register services.
 *
 * @return void
 */
public function register()
{
    $this->app->bind(ProductRepositoryInterface::class, ProductRepository::class);

}

之后,您可以将存储库注入控制器,如:

public function store(Request $request, ProductRepositoryInterface $productRepository)
{
    $newPro = $productRepository->createProduct($productData);
    ...
}

这是你的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);
    }
}

以及您的ProductRepositoryInterface:

<?php

namespace App\Repositories;

interface CategoryRepositoryInterface
{
    /**
     * @param  array  $productArray
     * @return Product
     */
    public function createProduct(array $productArray): Product;
}

Php相关问答推荐

SQLSTATE [42S02]:找不到基表或视图:1146 Table eshop. sessions不存在'''

WooCommerce中仅在单一产品和产品档案页面中将小数设置为大写

为什么在我的PHP联系人脚本中开机自检后出现未定义变量错误?

为什么只有最后一次点击的点赞/心形会按预期改变 colored颜色 ,而其他的保持正常 colored颜色 ?

如何使用索引加速和优化MySQL搜索

将WooCommerce WC_Order对象与wp_Schedule_Event一起使用

如果WooCommerce购物车在 checkout 时被清空,请重定向至store 页面

ANTLR4-lexer如何消耗更多的 token 并停止现有规则?

更改特定产品标签的 Woocommerce 产品名称

无法在 WordPress 上获取 JSON 数据

使用 PHP,我可以将 foreach 语句放入瞬态中吗?

如何使用 AJAX、PHP 和 MYSQL 在 Select 项目时在文本框中填充数据

如何在 PHP laravel 中将图像的透明背景转换为白色?

Windows 身份验证在 IIS 中验证什么?我可以在我的情况下禁用匿名身份验证吗?

Laravel的Storage::exists返回false,而file_exists返回true.

PHP preg_replace括号和方括号内的所有逗号

如何使用属性创建属性预设?

如何在php中获取大于50的年龄

Laravel 不会在回滚或刷新时删除表

如何使用 ACF 制作背景图片