typo3doctrine-dbal

Problem with instantiation of ConnectionPool in Extension


this description in the manual of the Query Builder Instantiation does not work.

My code is part of a symfony command:

namespace MyVendor\MyExtension\Command;

use TYPO3\CMS\Core\Database\ConnectionPool;

class myClassCommand extends Command {
  public function __construct(
    private readonly ConnectionPool $connectionPool,
  ) {
  }
}

This results in the following error:

Uncaught TYPO3 Exception Too few arguments to
function myClassCommand::__construct(), 0 passed
in /project-path/vendor/typo3/cms-core/Classes/Utility/GeneralUtility.php
on line 3000 and exactly 1 expected.

The reason is perhaps that the class command has an own __construct method which expects a parameter.

In former versions of TYPO3 i used this construction:

$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
  ->getQueryBuilderForTable($myTable);

which worked quite well. But according to the manual for version 12 it is not recommended to use GeneralUtility any more:

Never instantiate and initialize the query builder manually using dependency injection or GeneralUtility::makeInstance(), otherwise you will miss essential dependencies and runtime setup.

Any ideas? Is the manual wrong or do i have an error in my code?

Thanks!


Solution

  • In general, you can overwrite the default constructor of Symfony\Component\Console\Command\Command with custom constructor arguments without remaining the original constructor argument. See TYPO3\CMS\Backend\Command\CreateBackendUserCommand as an example, which also uses ConnectionPool as DI constructor argument.

    According to the error message, there is most likely something wrong with autoloading. Please make sure to always clear the TYPO3 cache and to dump autoload files (either in install tool or using composer for composer based installations).

    I think you misunderstood the manual in regards to GeneralUtility::makeInstance(). The documentation correctly points out, that QueryBuilder must not be instantiated manually using DI or GeneralUtility::makeInstance(). This does however not mean, that you can not use DI or GeneralUtility::makeInstance() to instantiate other classes (e.g. ConnectionPool).