【问题标题】:How to refactor parameters in if-else condition coming from a request laravel?如何在来自请求 laravel 的 if-else 条件下重构参数?
【发布时间】:2021-06-02 16:41:00
【问题描述】:

我的控制器中有这个功能,它检查参数请求并将其保存到我的表中以进行跟踪。但是我的if condition 太长了,因为每当添加新请求时,我都必须在每个请求中写入单独的if condition

这是我的代码:

public function storeTracking(Request $request)
{
    $traffic = new TrafficTracking();

    if ($request->has('gclid')) { // check if request = gclid
        $traffic->traffic_type = 'gclid';
        $traffic->traffic_value = $request->gclid;
    }

    if ($request->has('token')) { // check if request = token
        $traffic->traffic_type = 'token';
        $traffic->traffic_value = $request->token;
    }

    if ($request->has('fbclid')) { // check if request = fbclid
        $traffic->traffic_type = 'fbclid';
        $traffic->traffic_value = $request->fbclid;
    }

    if ($request->has('cjevent')) { // check if request = cjevent
        $traffic->traffic_type = 'cjevent';
        $traffic->traffic_value = $request->cjevent;
    }

    $traffic->save();

    return response()->json([
        'message' => 'success'
    ], 200);
}

对于if condition,有没有更短的方法?因为每当在控制器的storeTracking 函数中添加新请求时,代码都会很长。

【问题讨论】:

  • 如果有多个条件可以使用switch case或者使用三元运算符
  • @RushikeshGanesh 你能给我们举个例子吗?为了将来的目的,其他人可能会遇到同样的问题,他们可以复制它。

标签: laravel laravel-request laravel-controller


【解决方案1】:

你可以像这样尝试,但你需要验证或在 try catch 中你需要处理

这段代码可以是这样的

foreach ($request->except('_token') as $key => $value) {
    $traffic = new TrafficTracking();
    $traffic->traffic_type = $key;
    $traffic->traffic_value = $value;
    $traffic->save();
    break; // if you want single time execution 
} 

注意我不确定这是正确的答案,但这是解决这个问题的一个想法

【讨论】:

  • 是否可以使用foreach 函数,并且该函数内部只有typevalue 以及new TrafficTracking()save() 在foreach 之外?
  • 是的,你可以使用,但它会覆盖 $traffic->traffic_type 这就是为什么我这样写,我添加了 break 语句,所以它会循环一次
【解决方案2】:

使用三元运算符

(Condition) ? (Statement1) : (Statement2);

条件:要计算的表达式返回一个布尔值。

语句1:如果条件满足则执行的语句 结果是真实的状态。

语句 2:如果条件满足则执行的语句 导致错误状态。

使用开关盒

switch (n) {
    case label1:
        code to be executed if n=label1;
        break;
    case label2:
        code to be executed if n=label2;
        break;
    case label3:
        code to be executed if n=label3;
        break;
    ...
    default:
        code to be executed if n is different from all labels;
} 

【讨论】:

    猜你喜欢
    • 2016-03-01
    • 2020-04-24
    • 2020-11-30
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多