dongzi5062 2019-08-10 05:13
浏览 892
已采纳

Laravel:重构Controller store()和update()方法

I'm developing a Laravel Web App and I need insight in refactoring my Controller.

I noticed that my Controller store() and update() methods are VERY similiar. So similar that the only line that changes are the following: In the store() method I use $deck = new Deck(); and in the update() method I use $deck = Deck::find($id);. These are the only lines that change in these 140 line each methods inside the Controller.

How can I refactor or to where should I extract this code? My first thought was to create a Trait and put the method there, but that doesn't seem right, or does it?

  • 写回答

3条回答 默认 最新

  • dongyong6045 2019-08-10 05:18
    关注

    I won't advise on using a single method for both, but not knowing your use case you can use the firstOrNew helper method, which will return the Deck if it exists by the id given or it will make a new instance for you. So use this:

    Deck::firstOrNew(['id' => $id]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备