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.
1// app/Providers/AppServiceProvider.php 2 3use \Javoscript\MacroableModels\Facades\MacroableModels; 4use \App\User; 5 6public function boot() 7{ 8 MacroableModels::addMacro(User::class, 'sayHi', function() { 9 return "Hello, {$this->name}!";10 });11}12 13\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:
1MacroableModels::modelsThatImplement('sayHi');2/* [3 "App\User",4] */5 6// Return all macros for a model7MacroableModels::macrosForModel(\App\User::class);8// Get all registered macros9MacroableModels::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