需要从当前调用另一个控制器的功能?这是正确的做法吗?
Need to call function of another controller from current? Is that a right approach?
我的学术项目有了新的 laravel 5.7 设置。我想使用 laravel 制作药物提醒项目。
为此,我有 2 tables :
- 用户
- 医学
我有 User 和 Medicine 的模型和控制器。
控制器
- 医学控制器
- 用户控制器
- MedUserController
型号
- 用户
- 医学
- Med_User
在Model中,User和Medicine是多对多的关系。为了维护多对多,我链接 table User_Medicine 包含两个父 tables.
的外键
现在在控制器中,用户添加药品详细信息,应用程序应检查该药品是否已在数据库中。如果药物已经存在,应用程序应在链接 table 中将其 med_id 分配给 user_id。但是,如果药物不存在于数据库应用程序中,则应添加新的药物详细信息。这个过程写在MedUserController中。
现在的问题是,我在MedicineController@store 有添加药物的功能。我想从当前控制器 ( MedUserController ) 重用该功能。
最好的方法是什么。请提出建议。
控制器旨在详细说明输入并提供响应对象。也就是说,从另一个控制器调用一个控制器是一种不好的做法。
在你的情况下,你应该用 Repository Pattern 来处理这个,这意味着你有一个 class 负责数据库中的 creating/retrieving 个对象,你可以从任何 controller/class.
这是我要做的事的存根
public function controllerAction() {
$user = Auth::user();
$medicineData = request()->all();
$medicine = $this->medicineRepository->store($medicineData);
$user->medicines()->attach($medicine);
}
在存储库的 store
方法中,您可以检查药物是否已经存在或是否为新药物,并且您总是 return 一个 Medicine
对象。
我的学术项目有了新的 laravel 5.7 设置。我想使用 laravel 制作药物提醒项目。 为此,我有 2 tables :
- 用户
- 医学
我有 User 和 Medicine 的模型和控制器。
控制器
- 医学控制器
- 用户控制器
- MedUserController
型号
- 用户
- 医学
- Med_User
在Model中,User和Medicine是多对多的关系。为了维护多对多,我链接 table User_Medicine 包含两个父 tables.
的外键现在在控制器中,用户添加药品详细信息,应用程序应检查该药品是否已在数据库中。如果药物已经存在,应用程序应在链接 table 中将其 med_id 分配给 user_id。但是,如果药物不存在于数据库应用程序中,则应添加新的药物详细信息。这个过程写在MedUserController中。
现在的问题是,我在MedicineController@store 有添加药物的功能。我想从当前控制器 ( MedUserController ) 重用该功能。
最好的方法是什么。请提出建议。
控制器旨在详细说明输入并提供响应对象。也就是说,从另一个控制器调用一个控制器是一种不好的做法。
在你的情况下,你应该用 Repository Pattern 来处理这个,这意味着你有一个 class 负责数据库中的 creating/retrieving 个对象,你可以从任何 controller/class.
这是我要做的事的存根
public function controllerAction() {
$user = Auth::user();
$medicineData = request()->all();
$medicine = $this->medicineRepository->store($medicineData);
$user->medicines()->attach($medicine);
}
在存储库的 store
方法中,您可以检查药物是否已经存在或是否为新药物,并且您总是 return 一个 Medicine
对象。