【问题标题】:Laravel How not to Rewrite the Same code againLaravel 如何不再重写相同的代码
【发布时间】:2017-07-11 23:39:33
【问题描述】:

我有一个模型,称为 Tours 和控制器 ToursController,它使用 restful 方法(索引、显示、存储、编辑、更新等)。

现在我有了这个代码:

$names = request()->get('names');
$lastnames = request()->get('lastnames');
$hotels = request()->get('hotel');

在商店和更新中。所以我重复了两次相同的代码。而这只是重复代码的一个例子。

我想创建一个函数“getEverythingFromRequest()”

我可以在 Store 和 Update 方法中使用它。比如:

public function store (Request $request) {

getEverythingFromRequest();

dd($names[3];

}


public function store (Request $request) {

getEverythingFromRequest();

dd($hotels[2];

}

我该怎么做?在全球范围内,如何避免在 Controller 中重写相同的代码?

【问题讨论】:

  • 你试过firstOrCreate方法吗?在此处查看文档laravel.com/docs/5.4/eloquent#updates
  • 好方法,谢谢,我会用的。但我的问题更广泛:如何不写两次代码?:)

标签: laravel function duplicates


【解决方案1】:

有很多方法可以解决这个问题。一种方法是创建一个从您的请求中提取数组的存储库。 (我更新了我的代码以使用注入)。

控制器

public function store (GuestsRepository $repo, Request $request) {

  dd($repo->names);

}

存储库

<?php

namespace App;

class GuestsRepository
{
    public $names;
    public $lastnames;
    public $hotels;

    public function __construct(){
        $this->names = request()->get('names');
        $this->lastnames = request()->get('lastnames');
        $this->hotels = request()->get('hotel');
    }
}

【讨论】:

  • 谢谢你,牛仔。你能指出其他方式吗?)
  • 当然,你可以用很多方法来做这件事,除了重用代码你还想做什么?
猜你喜欢
  • 2022-01-02
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 2021-01-27
  • 2021-07-06
  • 2011-06-26
  • 1970-01-01
相关资源
最近更新 更多