Illuminate\Support\Traits\Tappable を use すると、クラスに tap() メソッドを追加できます。
trait Tappable{ public function tap($callback = null) { return tap($this, $callback); }}
つまりインスタンスメソッド版の tap() を提供するだけです。
use Illuminate\Support\Traits\Tappable;class ReportBuilder{ use Tappable;}$builder = new ReportBuilder();$builder = $builder->tap(function (ReportBuilder $instance) { logger()->debug('builder initialized');});
Tappable は Fluent API の途中で副作用を差し込みたいときに便利です。Macroable と Conditionable を組み合わせると、Laravelらしい拡張可能なビルダーを作れます。
1
フルーエントなクラスを作る
use Illuminate\Support\Traits\Conditionable;use Illuminate\Support\Traits\Macroable;use Illuminate\Support\Traits\Tappable;class QueryPresetBuilder{ use Macroable; use Conditionable; use Tappable; protected array $filters = []; public function where(string $key, mixed $value): static { $this->filters[$key] = $value; return $this; } public function toArray(): array { return $this->filters; }}