添加到控制器的内容和添加到模型的内容

Pif*_*fek 6 php methods model-view-controller private laravel

我有一个小问题。哪些数据保存在控制器中,哪些数据保存在模型中?我知道在模型中保留了应用程序的整个逻辑等,但是查询和帮助函数是什么?例如

控制器:

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
}
Run Code Online (Sandbox Code Playgroud)

我应该在哪里保留控制器或模型中的“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();
}
Run Code Online (Sandbox Code Playgroud)

我应该在控制器、项目模型还是属性模型中保留“deleteProperties”方法?并从这个模型调用这个方法?

Ale*_*nin 1

您应该保留类似服务类makeDirectory()中的方法并使用以下方式调用它:

$this->fileService->makeDirectory($directory);
Run Code Online (Sandbox Code Playgroud)

您应该将数据相关逻辑保留在模型类或存储库类中,并在控制器中使用它:

$this->model->getSomeData();
Run Code Online (Sandbox Code Playgroud)

您可能还想用谷歌搜索“胖模型,瘦控制器”。

关于辅助函数,您应该仅在真正需要时才使用它们。例如,isAdmin()是一个非常方便的全局帮助程序,但您永远不应该创建像getAllUsers()或这样的帮助程序Helpers::getAllUsers()