2

Both Symfony & Laravel allow you to never have to say specifically which class you need for a constructor, but they'll resolve it for you. When you do:

class ClassThatNeedsSomething
{
    public function __construct( ServiceToLookFor $service )
    ..

both of them know that they need to look for an object of type ServiceToLookFor in their service containers. Ok, but aren't classes resolved at run-time? Laravel is a framework built on top of PHP itself, it doesn't run before it and if it doesn't run before it, it means it has to instantiate itself in same environment (aka after all classes have been resolved to their files, etc.) as the others.

If there is a hook into classes such as __instantiated so you can dynamically resolve them there, it'd make sense, but then again...where do you write the code to hook into this?

To me, it feels like a chicken & egg problem.

How is this achieved?

  • 1
    This is done using the Reflection class in php. https://www.php.net/manual/en/class.reflectionclass.php. Using that class you can load classes and determine what is being injected into it and create auto-instantiation. – Rasclatt Dec 02 '19 at 03:10
  • @Rasclatt Was looking at it but just couldn't figure out HOW exactly. I'm looking for a dumbed down version of what the logic behind is. – Daniel Smith Dec 02 '19 at 03:11
  • 2
    @Rasclatt `determine what is being injected into it and create auto-instantiation.` that means, in my app, I'm merely declaring classes and then pass these declarations to Laravel, which will then, through Reflection, resolve their dependencies? Doesn't that mean Laravel has to have a factory mechanism? – Daniel Smith Dec 02 '19 at 03:13
  • 2
    @Rasclatt Found it! https://stackoverflow.com/questions/47200527/how-does-reflection-in-laravel-work – Daniel Smith Dec 02 '19 at 03:14

0 Answers0