Macroable dan Container Tags di Laravel
Definisi
Macroable trait memungkinkan menambah method ke class existing saat runtime (mix-in). Container tags (tag(), tagged()) mengelompokkan binding container agar bisa di-resolve sekaligus (misal semua Reporter).
Kapan dipakai
- Macroable: perlu tambah helper ke
Response,Collection,Strtanpa subclass (untuk DRY lintas project). - Container tags: saat satu fitur butuh banyak implementasi (plugins, listeners) di-inject bersama.
- Jangan over-macro: sulit dilacak kalau terlalu banyak method "gaib".
Cara kerja
Macro di Collection
use Illuminate\Support\Collection;
Collection::macro('toUpperKeys', function () {
return $this->mapWithKeys(fn($v, $k) => [strtoupper($k) => $v]);
});
collect(['a' => 1])->toUpperKeys(); // {'A': 1}Container tags
$this->app->bind(Logger::class, FileLogger::class);
$this->app->tag([FileLogger::class, DbLogger::class], 'loggers');
$loggers = $this->app->tagged('loggers'); // semua impl
foreach ($loggers as $l) { $l->log('hi'); }Struktur alur
Loading diagram...
Catatan implementasi
- Macro didefinisikan sekali (biasanya di service provider
boot()). - Method macro
function () { $thismerujuk instance class tersebut. - Tag berguna untuk pipeline/listeners; kombinasikan dengan interface agar typed.
- Untuk testing, macro perlu didaftarkan ulang (provider jalan di boot).
Kesalahan umum
- Macro di mana saja: sulit debug; daftarkan di provider khusus.
- Overuse macro: behavior "muncul dari nowhere" bingung tim.
- Tag tanpa interface:
tagged()return campuran tak terjamin tipe. - Lupa boot provider: macro belum terdaftar saat dipanggil.