[5.5] Allow macros to be registered using classes (in addition to closures) #19782
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
In line with the new validation rule classes and the thought that everything should be in its own class, this draft PR adds the ability to register macros using classes in addition to closures (be it for collection, request, etc).
How it can benefit
A messy service provider like so:
Can be reduced to just a few statements giving a better overview:
It's also neater to have everything separated so you don't have to go search where you registered a certain macro, it's all there in your project directory overview like any other class.
How to use
Create a macro (for a collection for instance) and have it implement the macro class:
Bind the macro to a method name like usual:
That's it!
Concerns
Losing the closure completely
Right now it's just weird you have to return a closure inside the handle method. I tried an implementation similar to the one already in place to have the class using the Macroable trait adopt the handle method from the child macro class as-is, but PHP won't let me.
Something like:
Unfortunately this only works for anonymous functions as it throws an exception when I want to bind MyMacro's method (now a closure) to another class' context. Any idea how to go about this?
Other
callable
typehint from themacro
method pose any issues? Perhaps a new method to register a macro class would be better.Feedback welcome!