wp-starter/macroable
Lightweight Macroable trait for PHP/Laravel-style macros. Add runtime methods to your classes, register macros and mixins, and call them like native methods—useful for extending objects without inheritance or boilerplate.
Installation:
composer require wp-starter/macroable
Add to composer.json under "extra":
"laravel": {
"macroable": true
}
First Use Case:
Extend a Laravel model (e.g., User) with a custom macro:
use WPStarter\Macroable\Macroable;
class User extends Authenticatable
{
use Macroable;
}
// Register a macro (e.g., in a service provider)
User::macro('fullName', function () {
return "{$this->first_name} {$this->last_name}";
});
// Usage:
$user = User::first();
echo $user->fullName(); // Outputs: "John Doe"
Key Files:
config/macroable.php (if published): Defaults and global settings.app/Providers/MacroServiceProvider.php: Register macros here (or use boot() in AppServiceProvider).Model Macros:
// In a service provider
User::macro('isAdmin', function () {
return $this->role === 'admin';
});
// Usage
if ($user->isAdmin()) { ... }
User::macro('activeOnly', function () {
return $this->where('active', true);
});
Service/Helper Macros:
Request, Response):
\Illuminate\Http\Request::macro('getIp', function () {
return $this->ip() ?? $this->header('X-Forwarded-For');
});
Conditional Macros:
when() to conditionally register macros:
if (config('app.env') === 'local') {
User::macro('debug', function () {
return $this->toArray();
});
}
Macro Groups:
User::macroGroup('permissions', ...)) or use traits to group logic.MacroServiceProvider for clarity.User::macro('testMacro', fn() => 'mocked');
$this->assertEquals('mocked', User::first()->testMacro());
/**
* @return string
*/
User::macro('fullName', function () { ... });
Macro Overwriting:
hasMacro() to check:
if (!User::hasMacro('fullName')) {
User::macro('fullName', ...);
}
Late Static Binding:
$className::macro()) unless using call_user_func().Performance:
Namespace Collisions:
User::macro('scopeActive', ...) vs. Model::macro('scopeActive', ...)).Macro Not Found:
boot()).Macro Not Working:
dd(\WPStarter\Macroable\Macroable::getMacros(User::class)) to list registered macros.Macroable trait.Custom Macro Storage: Override the default storage (e.g., cache macros in a database for shared hosting):
\WPStarter\Macroable\Macroable::setStorage(new DatabaseMacroStore());
Macro Events: Listen for macro registration/unregistration via events (if the package supports it; extend if needed):
event(new MacroRegistered(User::class, 'fullName'));
Dynamic Macro Loading: Load macros from config or files:
$macros = config('macroable.user');
foreach ($macros as $name => $callback) {
User::macro($name, $callback);
}
Publish Config:
php artisan vendor:publish --tag=macroable-config
macroable.php to:
Environment-Specific Macros: Use config to load environment-specific macros:
config(['macroable.macros.' . config('app.env') => [...]]);
How can I help you explore Laravel packages today?