Inject TypoScript Settings

Sometimes you need settings like TypoScript in a class which is not your controller. Inside a controller, the Extbase framework already injects the settings for you, so you are able to access them under $this->settings.

In all other classes it’s easy to let Extbase inject the settings for you. Just include the following code, and make sure you instantiate the class via \TYPO3\CMS\Extbase\Object\ObjectManager instead of \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance().

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
namespace DS\ExampleExtension\Service;

/*
 * Copyright (C) 2015  Daniel Siepmann <coding@daniel-siepmann.de>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;

/**
 * Example Service to demonstrate inject of settings.
 */
class SomeService
{
    /**
     * @var array
     */
    protected $settings = [];

    /**
     * Inject settings via ConfigurationManager.
     *
     * @param ConfigurationManagerInterface $configurationManager
     */
    public function injectConfigurationManager(ConfigurationManagerInterface $configurationManager)
    {
        $this->settings = $configurationManager->getConfiguration(
            ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS,
            'ExtensionName',
            'PluginName'
        );
    }
}

This will use Extbase inject mechanism of ObjectManager to inject the ConfigurationManager. Instead of persisting this instance as a property, we just use it to fetch the settings and persist them instead. As most developers are used to $this->settings from Controllers, I’m using the same convention in my classes.

This way the settings are available as a property in the class without any further work.

Just make sure you are using the \TYPO3\CMS\Extbase\Object\ObjectManager as pointed out above. It’s really important, as only this class will process the injects. \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance() doesn’t support this feature.

Further reading

Check out the post about TYPO3 (Extbase) Injection.