dependency-injectiontypo3hooktypo3-8.x

TYPO3 how to inject objectManager in hook?


Maybe it's just simple, but I can't figure it out.

TYPO3 8.7: I am programming a small hook: if a certain condition is met I want to send an email. Therefore I need the standalone view for the email template. But for the standalone view I need the object manager:

/** @var \TYPO3\CMS\Fluid\View\StandaloneView $emailView
$emailView = $this->objectManager->get('TYPO3\\CMS\\Fluid\\View\\StandaloneView');

At the beginning of my class I tried to inject the objectManager:

/**
 * @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
 */
protected $objectManager;

/**
 * @param \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager
 * @internal
 */
public function injectObjectManager(\TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager)
{
    $this->objectManager = $objectManager;
}

But it does not work: I run into an error: the objectManager is a null object. Which obviously means that the injection mechanism is not present in the hook.

How can this be achieved then?


Solution

  • Extbase Dependency Injection is not available in hooks, so you have to create instances of objects yourself.

    $standaloneView = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class)
    ->get(TYPO3\CMS\Fluid\View\StandaloneView::class);