Rintisch
Rintisch

Reputation: 483

TYPO3: Symfony command with arguments AND dependency injection

I made a command in TYPO3 which has arguments and dependency injection (DI). As I understood in symfony DI is made with the __construct method. But there I also have to state the argument which I want to pass to the command. So how is it done correctly?

Sources:

Versions: TYPO3 9.5.5, symfony 4.2.5

Say I want to pass one argument to the command AND inject the ObjectManager from TYPO3:

<?php

namespace Vendor\ExtensionName\Command;

use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;
use Symfony\Component\Console\Command\Command;

class SomeCommand extends Command 
{

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

    /**
     * @param \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager
     */
    public function __construct(
        string $cliParameter,
        \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager) 
    {
        $this->cliParameter = $cliParameter;
        $this->objectManager = $objectManager;
    }
}

Then I call this with

bin/typo3 extension_name:someCommand foo

(where foo is the $cliParameter)

I get

Uncaught TYPO3 Exception Cannot instantiate interface TYPO3\CMS\Extbase\Object\ObjectManagerInterface

So my question is: What did I wrong? What's the correct way to do this?

Upvotes: 5

Views: 2840

Answers (1)

Mathias Brodala
Mathias Brodala

Reputation: 6460

Symfony commands are unrelated to Extbase. So you cannot use DI before TYPO3v10. However, you can still get yourself an instance of the ObjectManager and then retrieve any object you need:

$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$exampleRepository = $objectManager->get(ExampleRepository::class);

If a class does not rely on Extbase or its DI, you can directly get an instance with GeneralUtility::makeInstance() instead.

Notice that with TYPO3v10 or newer you can use the native TYPO3 DI for commands instead.

Upvotes: 7

Related Questions