多层次的条件判断如何用 when 来构造

if (A) {
    if (A1) {
    } elseif (A2) {
    }
} elseif (B) {
    if (B1) {
    } elseif (B2) {
    }
}

如何用when来构造这些条件?
(别说把条件按组合用&&拼到一个括号里去)

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
leo
最佳答案

我从来不用 when,因为我很讨厌写闭包函数的 function

$builder = ModelClass::query()->where(shared conditions);
if (A) {
    if (A1) {
        $builder->where(special conditions 1);
    } elseif (A2) {
        $builder->where(special conditions 2);
    }
} elseif (B) {
    if (B1) {
        $builder->where(special conditions 3);
    } elseif (B2) {
        $builder->where(special conditions 4);
    }
}
5年前 评论
Rancy 3年前
讨论数量: 10
leo

我从来不用 when,因为我很讨厌写闭包函数的 function

$builder = ModelClass::query()->where(shared conditions);
if (A) {
    if (A1) {
        $builder->where(special conditions 1);
    } elseif (A2) {
        $builder->where(special conditions 2);
    }
} elseif (B) {
    if (B1) {
        $builder->where(special conditions 3);
    } elseif (B2) {
        $builder->where(special conditions 4);
    }
}
5年前 评论
Rancy 3年前
leo

我从来不用 when,因为我很讨厌写闭包函数的 function

$builder = ModelClass::query()->where(shared conditions);
if (A) {
    if (A1) {
        $builder->where(special conditions 1);
    } elseif (A2) {
        $builder->where(special conditions 2);
    }
} elseif (B) {
    if (B1) {
        $builder->where(special conditions 3);
    } elseif (B2) {
        $builder->where(special conditions 4);
    }
}
5年前 评论
Rancy 3年前

@leo 可是不用when的话,那么每次构造查询,都得把完整查询再写一遍岂不是代码很重复?

5年前 评论
leo

@kiyoma 当然不是,参考我上面的代码(刚刚调整了一下更能说明清楚)

5年前 评论

@leo 不好意思,前面没注意看。学到了,谢谢。

5年前 评论

@leo +1 讨厌写一个又一个的 function,啥时候 PHP 有原生的 Lambda 支持就好了... 想念 C# 的一堆语法糖。

5年前 评论

@leo 老师跳槽到了RightCapital了吗?

5年前 评论
leo

@Flourishing 是的

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!