如何创建一个单独的类来在表中创建新记录并通过控制器上的接口或外观调用它
我想重构我的控制器代码,该代码在表 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,
]);
...
}
现在为了重构此代码,我有两个选择:
1- 创建一个单独的方法在同一个控制器上,然后像这样调用它:
$newPro = self::createProduct($request->product_name,$request->product_name_english,$request->product_type,$request->category_product)
2- 创建一个单独的类并通过 interface
或 facade
调用它(最好的方法)
现在我想使用第二个选项,但我不知道真如何!
所以如果你知道请告诉我...
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先创建您的存储库服务提供者:
然后您应该在注册方法中映射接口和存储库(当然您也必须创建 ProductRepository 和 ProductRepositoryInterface),例如:
之后您可以将存储库注入到控制器中,例如:
这是您的 ProductRepository< /strong>:
和您的 ProductRepositoryInterface:
First create your repository service provider:
then you should map Interface and your Repository (ofcourse you must create ProductRepository and ProductRepositoryInterface too) inside register method like:
after that you can inject your repository to your controller like:
Here is your ProductRepository:
and your ProductRepositoryInterface: