Hello Magento dev community! I know, you all have used object manager directly to instantiate a class, somewhere while debugging or for any other purpose in your code. Like -
$objectManager->create(\Vendor\Module\Helper\Data::class);
But, have you ever wonder how object manager manages to instantiate the object of provided class, when provided class constructor has multiple dependencies?
This is Automatic Dependency Injection. Actually when we pass any class namespace to object manager, it checks for the class dependencies and automatically provide the constructor dependencies to create an instance.
But how Magento does this? Here come the role of Reflection class. Object manager uses PHPReflectionClass to look into the class constructor, then create object of each dependency and inject it to the class constructor in order to instantiate it.
Here is the snippet of code where this magic happens -
/**
* Read class constructor signature
*
* @param string $className
* @return array|null
* @throws \ReflectionException
*/
public function getConstructor($className)
{
$class = new \ReflectionClass($className);
$result = null;
$constructor = $class->getConstructor();
if ($constructor) {
$result = [];
/** @var $parameter \ReflectionParameter */
foreach ($constructor->getParameters() as $parameter) {
try {
$result[] = [
$parameter->getName(),
$parameter->getClass() !== null ? $parameter->getClass()->getName() : null,
!$parameter->isOptional() && !$parameter->isDefaultValueAvailable(),
$this->getReflectionParameterDefaultValue($parameter),
$parameter->isVariadic(),
];
} catch (\ReflectionException $e) {
$message = $e->getMessage();
throw new \ReflectionException($message, 0, $e);
}
}
}
return $result;
}
Thank you all. Happy Coding :)
Commentaires