PHP Laravel:比这些if语句更好的方法

时间:2018-12-10 16:49:33

标签: php laravel eloquent

我需要将佣金分配给新创建的价格。佣金可根据客户,类型和价格而变化。因此,如果存在类型佣金,则应首先获取它,后退到客户端,后退到默认值。

我的代码可以工作,但是感觉有点“ if-y”。也许有更好的方法吗?

  private function addDefaultOnlineCommission(Price $price)
   {
       $defaultCommission = (object)Commission::DEFAULT_COMMISSIONS;

       $typeCommission = $price->type->commissions()
           ->where('is_online', '=', true)->first();

       $clientCommission = $price->type->client->commissions()
           ->where('is_online', '=', true)->first();


       if (!$clientCommission && !$typeCommission) {
           $commission = $defaultCommission;
       }

       if ($clientCommission && !$typeCommission) {
           $commission = $clientCommission;
       }

       if ($typeCommission) {
           $commission = $typeCommission;
       }

       $price->commissions()->create([
           'commission_type'   => $commission->commission_type,
           'commission_value'  => $commission->commission_value,
           'min_value'         => $commission->min_value,
           'is_online'         => true,
           'valid_from'        => Carbon::now()->format('Y-m-d H:i:s'),
       ]);
   }

3 个答案:

答案 0 :(得分:6)

固执己见,但我会使用空合并运算符来处理它:

$commission = $typeCommission ?? $clientCommission ?? $defaultCommission;

这将使用第一个非空值。因此,它设置了从左到右的优先级。

答案 1 :(得分:2)

我认为这些函数看起来像“ if-y”,因为您的声明比必须的要复杂得多。另外,您始终会加载所有后备广告,这在每种情况下都不必要。我将重构该函数以仅在必要时加载下一个级别。看起来可能像这样:

private function addDefaultOnlineCommission ( Price $price ) {

    // load the type commission
    $commission = $price->type->commissions()->where( 'is_online', '=', true )->first();

    // if there is no type commission, check client commission
    if( empty($commission) ){
        $commission = $price->type->client->commissions()->where( 'is_online', '=', true )->first();
    }

    // if there is no client commission either, fall back to the default
    if( empty($commission) ){
        $commission = (object)Commission::DEFAULT_COMMISSIONS;
    }

    $price->commissions()->create( [
        'commission_type'  => $commission->commission_type,
        'commission_value' => $commission->commission_value,
        'min_value'        => $commission->min_value,
        'is_online'        => true,
        'valid_from'       => Carbon::now()->format( 'Y-m-d H:i:s' ),
    ] );

}

这不仅减少了功能的长度,还使它更具可读性。此外,还可以避免不必要的查询。

注意:您可以用is_null()替换empty(),因为first()对空结果返回null。

答案 2 :(得分:1)

怎么样?

   if (!$clientCommission && !$typeCommission) {
       $commission = $defaultCommission;
   } else if ($clientCommission && !$typeCommission) {
       $commission = $clientCommission;
   } else {
       $commission = $typeCommission;
   }