Javier Ugarte released a package called Laravel Macroable Models for adding methods to Laravel models on the fly:
The package offers developers an easy way of programmatically adding methods to Laravel Eloquent models. Behind the scenes, it makes use of Laravel’s macroable trait.
The idea of macorable models has controversy around it, but the package author describes his particular use-case and solution in his writeup about the package. As always, be sure to explore your use-case, and in general macroable models won’t be necessary for most use-cases.
With that said, let’s check out what this package provides:
You can define a macro for a model through a service provider boot()
method. The package keeps track of macros for each model.
// app/Providers/AppServiceProvider.php
use \Javoscript\MacroableModels\Facades\MacroableModels;
use \App\User;
public function boot()
{
MacroableModels::addMacro(User::class, 'sayHi', function() {
return "Hello, {$this->name}!";
});
}
\App\User::first()->sayHi();
As you can see in the example above, this package takes care of context binding so you can use $this
inside macro functions.
Here are a few more functions the package provides:
MacroableModels::modelsThatImplement('sayHi');
/* [
"App\User",
] */
// Return all macros for a model
MacroableModels::macrosForModel(\App\User::class);
// Get all registered macros
MacroableModels::getAllMacros();
Learn More
I want to reiterate that this package has a narrow, unique use-case. Typically, you wouldn’t need macros to define model methods on-the-fly. I’d recommend reading the author’s writeup about this package and his inspiration behind it.
You can learn more about this package, get full installation instructions, and view the source code on GitHub.
0 comments:
Post a Comment
Thanks