spatie/macroable
Add methods to any class at runtime with Spatie’s Macroable trait. Register macros with closures or callables and call them like native methods; macros are bound to the class instance for access to $this. Inspired by Laravel’s Macroable implementation.
Start by installing the package via Composer:
composer require spatie/macroable
Then apply the Spatie\Macroable\Macroable trait to any class you want to extend dynamically. The most immediate use case is augmenting existing classes (like service classes or value objects) with ad-hoc functionality without modifying their source — ideal for prototyping, testing, or plugin-style behavior injection. For example:
use Spatie\Macroable\Macroable;
class MyService
{
use Macroable;
public function doSomething() { return 'original'; }
}
$service = new MyService();
$service::macro('extended', fn() => 'extra behavior');
echo $service->extended(); // 'extra behavior'
StringMacros, CollectionMacros).Str, Collection) where Laravel’s core already uses Macroable, or build your own macroable services (e.g., custom mailers or payment gateways).User::macro('fullName', fn() => "{$this->first} {$this->last}").macro() are bound to the instance’s $this, so they can access properties and other methods — but be cautious with closures that capture variables; they’re evaluated at macro registration time, not call time.::macro() registers them on the class, but they’re invoked on instances (e.g., $obj->macroName()).macro('name', ...) again overwrites the previous macro — no warnings are issued. Use hasMacro() to guard against accidental overwrites.@method string someMacro()) or tools like barryvdh/laravel-ide-helper to improve DX.unsetMacro() or flushMacros() to avoid test pollution.How can I help you explore Laravel packages today?