2

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');
}

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?

lorenz
  • 4,538
  • 1
  • 27
  • 45

2 Answers2

6

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');
}
lorenz
  • 4,538
  • 1
  • 27
  • 45
2

As an alternative to lorenz answer, you could use the lifecycle-method initializeObject(). It will be called after dependency injection has been done.

Jost
  • 5,948
  • 8
  • 42
  • 72
  • 1
    I wouldnt. That's what constructors are there for-set things up. – Cedric Ziel Apr 28 '15 at 10:03
  • Another philosophy is this: The constructor should only used for construction once, when the object is created and then never again. Not even if it is thawn from a database or cache or something. Lifecycle methods are called in any case. But I guess both ways will work in TYPO3, and that won't change soon, so this is more of a theoretical thing. – Jost Apr 28 '15 at 10:13
  • That raises an immediate question: How often do you serialize Service Objects or Controllers? - The model should be anemic so where would this theoretical thing happen in the current state? – Cedric Ziel Apr 28 '15 at 10:29
  • In TYPO3 it would not happen, as far as I know, because most objects only live for the time of one request. But in other languages with a different execution model (e.g. Java), this might very well happen: If the controller/service/whatever is not needed, it can be frozen and put into some cache, and be thawn once it is needed again. Thus this is rather theoretical for TYPO3. – Jost Apr 28 '15 at 14:54
  • Exactly-that's why I'm asking. The label is TYPO3, so why mix concerns that dont matter in? – Cedric Ziel Apr 28 '15 at 14:56