如何在挂入TYPO3核心的类中使用DI?

时间:2016-09-30 08:07:34

标签: typo3

有没有办法在挂钩Core的类中使用依赖注入(使用Hook)?

1 个答案:

答案 0 :(得分:1)

DI要求使用extbase对象管理类。但是,钩子中的对象通常用\TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance实例化,不支持DI。

但是,您可以在钩子和服务类之间添加代理层,使用extbase objectManager进行管理。

以下是使用构造函数注入的示例:

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;

class YourHook {
    public function yourMethod(value)
    {
        $this->objectManager = $this->getObjectManager();
        $yourService = $this->objectManager->get(YourService::class);
        $result = $yourService->process($value);

        return $result;
    }

    protected function getObjectManager()
    {
        return GeneralUtility::makeInstance(ObjectManager::class);
    }

}

class YourService {
    public function __construct(OtherService $otherService)
    {
        $this->otherService = $otherService;
    }

    public function process($value)
    {
        return $this->otherService->doFancyStuff($value);
    }
}

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3_hook.php']['hookName'][] = 'EXT:your_ext/Classes/YourHook.php:YourHook->yourMethod'