Calling a CommandController from ActionController in PHP/TYPO3 Extbase

1.1k views Asked by At

I wrote a Command Controller that handles data import from an URL. pseudo-syntax is like this:

class ImportCommandController extends \TYPO3\CMS\Extbase\Mvc\Controller\CommandController
{
  public function importCommand($auth){
    $data = file_get_content();
  }
}

this works. But when I try to call that command from the Action Controller of my backend Module I get errors. Heres the code: ActionController:

class ImportController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
    /**
     * @var \Vendor\MyExt\Command\ImportCommandController importCommandCtrl
     * @inject
     */
    protected $importCommandCtrl;

    public function importAction()//($url,$usr,$pass)
    {
        //$this->importCommandCtrl = GeneralUtility::makeInstance('Vendor\MyExt\Command\ImportCommandController');
        $this->importCommandCtrl->testCommand();
    }
}

When I call importAction() like this, I get:

"Call to a member function testCommand() on null"

When I uncomment the makeInstance, I get:

"Call to a member function get() on null"

Sadly, this topic is documente rather poorly in the TYPO3 Docs. Can someone help me on this or point me to the right direction?

2

There are 2 answers

3
Daniel On BEST ANSWER

I'd like to slightly alter the answer already given by René and add some code examples. I also recommend to put your import logic into a dedicated class, e.g. ImportService:

namespace Vendor\MyExt\Service;
use TYPO3\CMS\Core\SingletonInterface;
class ImportService implements SingletonInterface
{
    public function importData()
    {
       // import logic goes here
    }
}

You can now inject this class as a dependency of your CommandController and your ActionController:

class ImportController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
    /**
     * @var \Vendor\MyExt\Service\ImportService
     * @inject
     */
     protected $importService;

    public function importAction()
    {
        $this->importService->importData();
    }
}

class ImportCommandController extends \TYPO3\CMS\Extbase\Mvc\Controller\CommandControlle
{
    /**
     * @var \Vendor\MyExt\Service\ImportService
     * @inject
     */
    protected $importService;

    public function importCommand()
    {
        $this->importService->importData();
    }
}
0
René Pflamm On

The use of an CommandController in an ActionController is not recommended because they have different envoiroment variables.

If you want to use some code on more position it's recommanded to use Utility classes.

So create an Class in the my_ext/Classes/Utility/ directory call the class something like ImportUtility and try to code your import independed from some controller.