我有个小问题。哪些数据保存在 Controller 中,哪些保存在模型中?我知道在模型中保留了应用程序等的整个逻辑,但是什么是查询和帮助函数?例如
Controller :
public function add(Request $request)
{
$item = new Item()
$item->name = $request->name;
$item->save();
$this->makeDirectory();
}
private function makeDirectory()
{
//make a directory with photo this product
}
我应该在 Controller 或模型中的什么地方保留“makeDirecory”方法?
这是另一种情况,我会从另一个表中删除产品和引用。
public function delete(Items $id)
{
$id->delete();
$this->deleteProperties($id->properties); // $id->properties is a method from Items model with references to table Properties
}
private function deleteProperties(Properties $id)
{
$id->delete();
}
我应该在 Controller 、项目模型还是属性模型中保留“deleteProperties”方法?并从此模型调用此方法?
最佳答案
你应该在 service class 中保留像 makeDirectory()
这样的方法并调用它:
$this->fileService->makeDirectory($directory);
你应该 keep data related logic in model classes or repository classes并在 Controller 中使用它:
$this->model->getSomeData();
您可能还想在 google 上搜索“胖模型,瘦 Controller ”。
关于辅助函数,你应该只在你真正需要的时候使用它们。例如,isAdmin()
是一个非常方便的全局帮助程序,但您永远不应该创建像 getAllUsers()
或 Helpers::getAllUsers()
这样的帮助程序>
关于php - 添加到 Controller 的内容和添加到模型的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48109333/