如何在构造函数中使用注入的对象? [英] How can I use an injected object in the constructor?
问题描述
我在Extbase扩展中有一个服务类,并希望使用ObjectManager在构造函数中创建对象的实例.
I have a service class in my Extbase extension and want to use the ObjectManager to create an instance of an object in the constructor.
/**
* @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
* @inject
*/
protected $objectManager;
public function __construct() {
$this->standaloneView = $this->objectManager->get('TYPO3\CMS\Fluid\View\StandaloneView');
$this->standaloneView->setFormat('html');
}
不幸的是,这不会因错误Call to a member function get() on null
而失败,因为注入的类在构造函数中似乎不可用.如何在构造函数中使用注入的类?
Unfortunately this doesn't fails with an error Call to a member function get() on null
because the injected class doesn't seem to be available in the constructor. How can I use an injected class in the constructur?
推荐答案
要实现这一点,我可以使用所谓的构造函数注入.将ObjectManagerInterface定义为构造函数的参数,然后由Extbase自动注入:
To achieve this, I can use so-called constructor injection. The ObjectManagerInterface is defined as an argument of the constructor and then automatically injected by Extbase:
/**
* @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
*/
protected $objectManager;
public function __construct(\TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager) {
$this->objectManager = $objectManager;
$this->standaloneView = $this->objectManager->get('TYPO3\CMS\Fluid\View\StandaloneView');
$this->standaloneView->setFormat('html');
}
这篇关于如何在构造函数中使用注入的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!