什么是 Conditionable trait
Illuminate\Support\Traits\Conditionable trait 为对象添加了 when() 与 unless() 方法。它的特点是可以在方法链中按条件分支执行处理。
实际源码位于
src/Illuminate/Conditionable/Traits/Conditionable.php,通过别名 Illuminate\Support\Traits\Conditionable 引用。基本用法
when() — 条件为真时执行
unless() — 条件为假时执行
unless() 是 when() 的相反版本。条件为假时执行回调。
方法链得以延续的原因
当回调返回值为null 时,将返回 $this(使用该 trait 的对象)。当回调返回非 null 值时,就使用该返回值。
null)返回的是 $this。
无参数调用 — HigherOrderWhenProxy
不传参数调用when() 时会返回 HigherOrderWhenProxy。这样可以稍后再设置条件。
传入闭包作为值
若第 1 个参数是闭包,则以该闭包的返回值作为条件。在 QueryBuilder 中的典型模式
使用when() 构建动态查询是最常见的用途。
在自定义类中使用 Conditionable
只需use 该 trait,就能获得 when() / unless() 能力。
在 Mail、Notification、Response 中的应用
when() 也可用于邮件、通知和响应的构建。
与 tap() 的区别
tap() 与 when() 看似相似,但目的不同。
下一步
集合的高阶消息
了解
$collection->map->method() 这类语法的机制与实用用法。