Execute repository functions in scheduler task

让人想犯罪 __ 提交于 2019-12-05 07:19:38

You are getting this php error, because you instanciated your controller with makeInstance(). If you use makeInstance to get the objectManager (\TYPO3\CMS\Extbase\Object\ObjectManager) and use $objectManager->get('TYPO3\ExtName\Controller\SampleController'), the dependency injection inside your controller will work (e.g. your repository).

But you can use the objectManager to get the repository right away, so you dont have to call a controller action:

Something like this:

namespace TYPO3\ExtName\Task;

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\ExtName\Domain\Repository\SampleRepository;
use TYPO3\ExtName\Domain\Model\Sample;
use TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface;

class SampleTask extends \TYPO3\CMS\Scheduler\Task\AbstractTask {

    public function execute() {
        $objectManager = GeneralUtility::makeInstance(ObjectManager::class);
        $sampleRepository= $objectManager->get(SampleRepository::class);
        $new = new Sample();
        $new->setName('test');
        $sampleRepository->add($new);
        $objectManager->get(PersistenceManagerInterface::class)->persistAll();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!