duancuisan2503 2018-12-20 11:18
浏览 100

我应该把模型创建代码放在哪里? [关闭]

Let's assume I have User model that related to models Image, Card, etc. That means when I create a new user, I should create Image and Card instances along with it, e.g. I have something like this in my controller's store method:

DB::beginTransaction();
try {
    $user->saveOrFail();

    $imageObj = new Image();
    $imageObj->user_id = $user->id;
    // set the other fields
    $imageObj->saveOrFail();

    $cardObj = new Card();
    $cardObj->user_id = $user->id;
    // set the other fields
    $cardObj->saveOrFail();
    .......................
    DB::commit();
  }

  return redirect('some');
}

For more than 2 related models there is too more code in the controller, so is there any thoughts or recommendations on where to put this code for better scalability?

  • 写回答

1条回答 默认 最新

  • duanbi3786 2018-12-20 11:27
    关注

    I would choose Factory. With this pattern you can easily create your new object and along with it anything you need. You juste need to pass the right parameters to your service.

    check these docs for creating Factory pattern in SYmfony https://symfony.com/doc/current/service_container/factories.html

    评论

报告相同问题?

悬赏问题

  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退