Concrete TYPO3 Dependency Injection examples
Published: , Updated:
Tested with TYPO3: 10 LTS
Introduction ¶
Some real world examples on how to use the Symfony Dependency Injection in TYPO3. E.g. how to inject TypoScript settings or database query builder.
Don't expect to many explanations here. These are already available, see links at bottom. Instead, this blog post contains concrete examples as reference and copy & paste.
Inject DB Connection and QueryBuilder ¶
Given the new Dependency Injection, one can inject a concrete QueryBuilder
instance, or Database Connection. As TYPO3 allows configuring multiple different database servers, developers need to fetch a proper instance based on the concrete database table. This involves some unnecessary code, which can be removed thanks to the Dependency Injection.
services:
_defaults:
autowire: true
autoconfigure: true
public: false
DanielSiepmann\Tracking\:
resource: '../Classes/*'
dbconnection.tx_tracking_pageview:
class: 'TYPO3\CMS\Core\Database\Connection'
factory:
- '@TYPO3\CMS\Core\Database\ConnectionPool'
- 'getConnectionForTable'
arguments:
- 'tx_tracking_pageview'
querybuilder.tx_tracking_pageview:
class: 'TYPO3\CMS\Core\Database\Query\QueryBuilder'
factory:
- '@TYPO3\CMS\Core\Database\ConnectionPool'
- 'getQueryBuilderForTable'
arguments:
- 'tx_tracking_pageview'
DanielSiepmann\Tracking\Domain\Repository\Pageview:
public: true
arguments:
- '@dbconnection.tx_tracking_pageview'
The corresponding PHP could look like:
namespace DanielSiepmann\Tracking\Domain\Repository;
use TYPO3\CMS\Core\Database\Connection;
class Pageview
{
/**
* @var Connection
*/
private $connection;
public function __construct(
Connection $connection
) {
$this->connection = $connection;
}
}
Inject TypoScript Settings ¶
Back in the old days, you could inject the TypoScript Settings into Extbase classes, see my old blog post. Given the new Dependency Injection, those can be injected into all classes, with no additional code inside the class:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
Vendor\ExtName\:
resource: '../Classes/*'
extbaseSettings.ExtName.PluginName:
class: 'array'
factory:
- '@TYPO3\CMS\Extbase\Configuration\ConfigurationManager'
- 'getConfiguration'
arguments:
$configurationType: 'Settings'
$extensionName: 'ExtName'
$pluginName: 'PluginName'
Vendor\ExtName\Domain\PeriodCreation\DataHandler:
arguments:
$settings: '@extbaseSettings.ExtName.PluginName'
The TypoScript settings are injected as plain PHP array into the constructor argument $settings
.
Further reading ¶
That are some concrete examples. For further information, check: