written: 2023-01-16
#from resolve() dark magic to expected dark magic
I am talking about the magic resolver of Laravel resolve() that you see in many articles and tutorials. If you haven't already, I suggest you learn how does container and magic binding resolver work in Laravel, as it changes how you approach things in the long run.
#The old way
/** @var MyCustomClass $instance */ $instance = resolve(MyCustomClass::class);
Pros:
- can resolve any kind of type
- shorter signature
Cons:
- can resolve any kind of type
- requires docblock for autocompletion
- refactoring code may not be fully automatic
- prone to typos in docblock
#The new way
$instance = (static fn():MyCustomClass => resolve(MyCustomClass::class)());
Pros:
- ensures the resolution is of correct type
- automatic and ensured autocompletion in IDE
- easy refactoring of the code and finding usage points
Cons:
- longer signature
Till next time, stay sexy and hydrated.