back home
thumbnail

Self calling resolve function with return type hint

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.

Stack 2023 - going cheaper fail
Stack 2023 - going cheaper fail
A-Frame Cabin - review
A-Frame Cabin - review
Stack 2023 - kubernetes with Rancher
Stack 2023 - kubernetes with Rancher
Volkswagen T2 Camper Van - review
Volkswagen T2 Camper Van - review
Laracon EU Lisbon 2023
Laracon EU Lisbon 2023
Stack 2023 - review the old way
Stack 2023 - review the old way
Self calling resolve function with return type hint
Self calling resolve function with return type hint
harry-potter-express - Hogwarts™ Express
harry-potter-express - Hogwarts™ Express
Volkswagen T2 Camper Van - pending
Volkswagen T2 Camper Van - pending
Snowboarding again - on the slopes
Snowboarding again - on the slopes
Snowboarding again - a gift to me
Snowboarding again - a gift to me
PhpStorm UI 2023
PhpStorm UI 2023