I'm trying to do something new with virtual types. I understand that you can create these in your di.xml
and use them as arguments for other types in di.xml
. But can I also declare a virtual type and use it in a constructor in a PHP class?
For example: I'm trying to do something like this:
<virtualType name="Vendor\Module\Logger\Handler"
type="Magento\Framework\Logger\Handler\Base">
<arguments>
<argument name="filePath" xsi:type="string">/var/log/custom.log</argument>
</arguments>
</virtualType>
And:
public function __construct(
\Vendor\Module\Logger\Handler $logger
) {
$this->logger = $logger;
}
But this does not work. I also tried:
<preference for="Vendor\Module\Logger\Handler" type="custom_logger"/>
<virtualType name="custom_logger"
type="Magento\Framework\Logger\Handler\Base">
<arguments>
<argument name="filePath" xsi:type="string">/var/log/custom.log</argument>
</arguments>
</virtualType>
With the same PHP code, but the results are the same. I get a ReflectionException
that class Vendor\Module\Logger\Handler
does not exist.
I find this odd, because the way I always understood, the Object Manager uses reflection to see what classes are required in the constructur, and uses the di.xml
configuration on it's turn to bring this back to a class. So why isn't this working with a virtual type?