Study guide · Events, Dependency Injection and Extending

Extending TYPO3 without touching the core

As of November 15, 2026 · TYPO3 14.3 LTS · about 19 min read

This page shows you the clean ways to extend TYPO3: dependency injection, events, hooks, conditions and, as a last resort, the XCLASS.

All examples belong to the extension my_extension, which manages conferences. It has an importer, a geocoder for venues and its own TypoScript condition.

Extend instead of modify

Composer manages the vendor folder on its own. Every Composer install or update rewrites the packages, and your change silently disappears. The folder is also usually listed in .gitignore, so it never reaches the live system.

That is why customizations belong in your own extension. TYPO3 recommends its extension points in this order:

  • PSR-14 events are the most important way.
  • Hooks are older extension points. No new ones are added.
  • Configuration points such as user functions in the TCA or your own service via dependency injection.
  • The XCLASS replaces an entire class and is the last resort.

Not every public core method is an official extension point. What stays stable is governed by the core API and the deprecation policy. Anything marked @internal is not part of it.

Two principles stand behind this. Loose coupling means two parts know as little about each other as possible, for example only an interface. Each part can then be changed, tested and replaced alone. Interfaces, events and dependency injection help, while static calls and global variables do harm.

Inversion of control means the framework calls your code at defined points, not the other way round. This is the Hollywood principle: don't call us, we'll call you. In TYPO3 the container creates your classes, the event dispatcher calls your listeners, and Extbase calls your controller action.

Software can react to events in several ways: with the observer pattern, with a dispatcher and listeners, with callbacks and hooks, or between systems with message queues.

Dependency injection and the container

With dependency injection, a class does not build its dependencies, it receives them. The DI container is in control of creating them.

TYPO3 uses the Symfony container. It implements PSR-11, and this standard knows only two methods: get() fetches a service, has() asks whether it exists.

Constructor injection is recommended. You declare the dependency as a constructor parameter, and the container passes in a matching instance by type. This is autowiring.

final class ConferenceImporter
{
    public function __construct(
        private readonly ConferenceRepository $conferenceRepository,
    ) {}
}
Code example. The importer receives the ConferenceRepository through its constructor.

The benefits: the dependencies are visible in the signature. In a test you pass in a test double. The implementation can be swapped by configuration. And the class only knows interfaces, not how its dependencies are created. Dependency injection does not resolve circular dependencies, they cause errors in the container.

The second form is method injection through public methods whose names start with inject. It is meant for base classes such as the Extbase ActionController. Your controllers keep their own constructor, and the core can add dependencies without breaking them. TYPO3 supports no other forms.

Tell services and data objects apart:

  • A service comes from the container, for example a controller, repository, listener or logger. Services are shared by default and should therefore not keep state.
  • A data object such as a domain model, a value object or an event is created with new or from the database. It gets no injection.

You only need GeneralUtility::makeInstance() where dependency injection is not possible. If it fetches a service from the container, the service must be public. With constructor injection this does not matter.

The Services.yaml file

How the container treats your classes is defined in Configuration/Services.yaml, or alternatively in a Services.php. Without it, constructor dependencies are not resolved. The composer.json only makes sure PHP finds the classes.

services:
  _defaults:
    autowire: true
    autoconfigure: true
    public: false

  MyVendor\MyExtension\:
    resource: '../Classes/*'
    exclude: '../Classes/Domain/Model/*'
YAML example. The defaults are autowire, autoconfigure and public false. All classes from the Classes folder become services, except the domain models.
  • autowire resolves dependencies from the types in the constructor.
  • autoconfigure adds tags based on interfaces, base classes or attributes. That is how a listener with AsEventListener or a command with AsCommand is registered without any further entry.
  • public false saves performance. You make single services public with the Autoconfigure attribute and its public option.
  • resource decides which classes the container knows.

Use the cache:flush command or the Install Tool under System, Maintenance, Flush Caches. The backend toolbar button clears the container only in the Development context, not in Production. A container broken by a bad Services.yaml does not heal itself.

Two implementations: The controller asks for a GeocoderInterface. One implementation would be linked automatically. With two, the OpenStreetMapGeocoder and the GoogleGeocoder, the container reports an error. The solution is an alias: the AsAlias attribute with the interface on the preferred class, or an entry in the Services.yaml.

  MyVendor\MyExtension\Geocoder\GeocoderInterface:
    '@MyVendor\MyExtension\Geocoder\OpenStreetMapGeocoder'
YAML example. The GeocoderInterface points to the OpenStreetMapGeocoder as an alias.

More Symfony tools:

  • Environment variables: the Autowire attribute with its env option, or an env placeholder in the Services.yaml. The value is read at runtime, without a cache flush.
  • Collections: AutoconfigureTag on the ExporterInterface marks every exporter, and AutowireIterator in the constructor of the ExportService collects them all.
  • Decorator: A class with AsDecorator receives the original service through AutowireDecorated and passes the calls on, for example to log before and after. Everyone then gets the decorator. An XCLASS, in contrast, works through inheritance.
public function __construct(
    #[Autowire(env: 'MYEXT_API_URL')] private readonly string $apiUrl,
    #[AutowireIterator('myext.exporter')] private readonly iterable $exporters,
) {}
Code example. The constructor receives the API address from an environment variable and all services tagged myext.exporter.

A dependency is missing? Check autowire and resource in the Services.yaml, flush the caches, and make sure each interface has an implementation or an alias.

How PSR-14 events work

PSR-14 is a PHP standard for event dispatchers. At defined points, the core passes an event object to all listeners. No core file is touched, so your customization survives updates.

PSR-14 knows five building blocks:

  • The event is a plain object with the data. Setters exist only for what listeners may change.
  • The listener is the class that reacts. If you listen to an event, you write a listener.
  • The emitter is the code that triggers the event.
  • The dispatcher calls the listeners one after another.
  • The listener provider gives it the listeners for an event.
Emitter, such as the importer dispatch($event) Dispatcher EventDispatcherInterface Listener Provider returns all listeners for the event The dispatcher calls them in turn Listener 1 my_extension Listener 2 seo Listener 3 others The same event comes back The emitter reads the changed values Order only via before and after
One event, any number of listeners. The emitter knows none of them.

Any number of listeners from different extensions may react to an event. A second one does not replace the first, and new reactions need no change to the trigger.

The names of core events help: Before comes before an operation, After comes after it, and Modify offers to change a result. The name does not express a priority.

The deprecation policy applies to core events, only their constructor arguments may change. Events do not need a common base class.

Writing a listener

The simplest way is the AsEventListener attribute on the class. The __invoke() method receives the event, and TYPO3 recognizes it by the type of the parameter.

#[AsEventListener(identifier: 'my-extension/replace-placeholder')]
final readonly class ReplacePlaceholderListener
{
    public function __invoke(AfterCacheableContentIsGeneratedEvent $event): void
    {
        $event->setContent(str_replace('###YEAR###', date('Y'), $event->getContent()));
    }
}
Code example. A listener with the AsEventListener attribute and a unique identifier. Its invoke method receives the AfterCacheableContentIsGeneratedEvent, reads the page content and writes it back with a placeholder replaced.

The event arrives after the cacheable part of the page has been rendered, and the change ends up in the cache too. With disableCaching() the listener could prevent storing it.

The attribute knows five options:

  • identifier is the unique identifier.
  • before and after name the identifier of another listener and so set the order. There is no numeric priority.
  • event names the event class if the parameter type is not enough.
  • method names a different method instead of __invoke().

The attribute may also sit on several methods of one class, each becoming its own listener. Without the event option, the first parameter type counts, and a union type means several events. The class must be autowired for this. Instead of the attribute, the event.listener tag in the Services.yaml works too.

Replacing someone else's listener: Register your listener with exactly the identifier of the other listener. Then only yours runs. Add the other extension as a dependency in your composer.json, so your registration is loaded later.

The dispatcher is a normal PSR-14 implementation. So you can also catch events from third-party PHP libraries.

A few core events:

  • ModifyUrlForCanonicalTagEvent changes the URL in the canonical tag of EXT:seo with setUrl(). The MetaTag API does not help here, because the canonical is a link element.
  • BeforeMailerSentMessageEvent arrives before every mail is sent, for example to add an extra header. The After event only informs you afterwards.
  • ModifyButtonBarEvent adds buttons to the header bar of backend modules.

Dispatching your own events

After every import, my_extension should inform other extensions without knowing them. A direct call or an XCLASS would couple them tightly. So the importer dispatches its own event, and anyone interested registers a listener.

  1. Create the event class in Classes/Event, its name ends in Event.
  2. Offer only the data listeners need. Add setters only for values they may change.
  3. Get the EventDispatcherInterface from the Psr namespace via dependency injection. In Extbase controllers it is already there.
  4. Trigger the event with dispatch(). You get the same object back, possibly changed by listeners.
$event = $this->eventDispatcher->dispatch(
    new AfterConferencesImportedEvent($conferences)
);
$conferences = $event->getConferences();
Code example. The importer passes a new AfterConferencesImportedEvent to dispatch and then reads the conferences from the returned event.

Never hand the whole controller to the event, as too much context couples listeners to your internals. An event only needs setters when listeners should adjust data the emitter keeps using. For plain notifications, an immutable event is enough.

PSR-14 describes four use cases: one-way notification, object enhancement or modification, collection of contributions from several listeners, and the alternative chain, where one listener ends further processing.

For the last case, the event implements the StoppableEventInterface. Before each listener, the dispatcher calls isPropagationStopped() and stops as soon as it returns true.

When a listener stays silent

  • The module System, Configuration shows under Event Listeners (PSR-14) all registered listeners with identifier and order. It comes from the lowlevel extension and is visible to administrators only.
  • The Admin Panel shows under Debug, Events which events a frontend request actually dispatched.

Since TYPO3 14, the former Admin Tools group is called System, and the former System group is called Administration.

Hooks, TCA functions and XCLASS

Hooks are older places where the core calls registered functions. You register them in ext_localconf.php under SC_OPTIONS. Events gradually replace them, in TYPO3 14 for example in the form framework. For saving in the DataHandler, the hook is still common.

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = MyHook::class;
Code example. The class MyHook is added to the DataHandler's processDatamapClass list. The DataHandler then calls its methods on every save.

There are two kinds:

  • Object hooks: The core creates the class with GeneralUtility::makeInstance() and calls a defined method, as in the DataHandler.
  • Function hooks: What is registered is a class and a method. The core calls it with GeneralUtility::callUserFunction(), passing a parameter array and the calling object.

User functions in the TCA are another extension point. With itemsProcFunc, a select field fetches its options at runtime, for example from an API. That way the TCA stays static. Similar options exist for display conditions and for the postModifiers of slug fields.

'itemsProcFunc' => MyItems::class . '->getItems',
TCA excerpt. itemsProcFunc points to the method getItems of the class MyItems.

The XCLASS replaces a class completely. Your class extends the original, overrides individual methods, and TYPO3 creates it wherever it would create the original. You register it in ext_localconf.php.

$GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][Original::class] = [
    'className' => MyXclass::class,
];
Code example. Under SYS, Objects, your own class is entered for the original class under the key className.
Is there a matching event? yes Listener AsEventListener no Is there a hook or a TCA user function? yes Use the hook itemsProcFunc, … no Does the class come as a service from the container? yes Alias or decorator no XCLASS Last resort: only one XCLASS per class, breaks easily on updates Top to bottom: event first, XCLASS last
The event first, the XCLASS last.

The limits of the XCLASS:

  • It only works if the class is created through GeneralUtility::makeInstance() or the container.
  • It does not work for static, abstract or final classes, and private methods cannot be overridden.
  • Only one XCLASS per original class is active.
  • It depends on the internals of the original and can break with every update.

For Extbase controllers, the XCLASS itself must be a service in the container. And PHP does not inherit attributes. If you override an action with Authorize or RateLimit, you repeat these attributes and those on the parameters. Otherwise the action is unprotected.

Conditions, feature toggles and the registry

The Symfony Expression Language evaluates conditions in TypoScript and TSconfig and in site base variants. Since TYPO3 14 it also powers the limitToPages option of route enhancers. Fluid does not use it, f:if has its own syntax.

Variables have no dollar sign, and there are no control structures. Conditions are combined with and, or and not. On top of that come in for lists, matches for regular expressions and the tilde for concatenation. An expression can return any value, and TypoScript turns it into true or false.

[frontend.user.isLoggedIn]
[12 in tree.rootLineIds]
[tree.pagelayout == "pagets__home"]
[3 in frontend.user.userGroupIds]
[applicationContext matches "/^Development/"]
[traverse(request.getQueryParams(), 'tx_news_pi1/news') > 0]
Six TypoScript conditions: a logged-in frontend user. Page 12 with all its subpages. Backend layout home, inherited too. User group 3. The Development context with its sub-contexts. A news ID in the URL, read safely with traverse.
  • The uid in the page variable only matches the page itself, the rootline covers the whole subtree.
  • The backend_layout field is empty on inheriting subpages, while tree.pagelayout holds the layout that applies.
  • Directly accessing a missing array element fails, while traverse() returns an empty string.
  • Two equals signs only match the exact context, matches also catches sub-contexts.
  • Old notations like loginUser or globalVar have not existed since TYPO3 10.

Your own functions: For a condition conferenceIsRunning(), you register a provider for the typoscript context in Configuration/ExpressionLanguage.php. It names a function provider that returns the functions through getFunctions(). System, Configuration shows the active providers.

Feature toggles switch on a new implementation next to the old one. They apply system-wide and live in the global configuration under SYS, features. You switch core toggles in the module System, Settings under Feature Toggles. Your own toggles do not show up there. Your extension sets their default value in ext_localconf.php.

$GLOBALS['TYPO3_CONF_VARS']['SYS']['features']['myExtensionNewList'] ??= true;
Code example from ext_localconf.php. The toggle myExtensionNewList gets the default value true if no value is set yet.

In PHP you call isFeatureEnabled() on the Features class. TypoScript has the feature() function, and Fluid has the f:feature ViewHelper. The name starts with the extension name and contains neither enable nor disable nor a negation.

The registry pattern is a central place that stores values under a key for access from anywhere. Examples are the IconRegistry and the system registry. The downside is a hidden, global dependency. The Registry class stores key and value pairs per namespace in the sys_registry table. Its get() method accepts a default value in case nothing is there. It suits small things like the time of the last import, not session or cache data.

Key points

  • Never change the vendor folder. The XCLASS is the last resort.
  • Constructor injection is the standard. Services are shared, models and events are created with new.
  • Always flush the caches after changing the Services.yaml.
  • Two implementations of one interface need an alias.
  • A listener gets the AsEventListener attribute, and before and after control the order.
  • You trigger your own events with dispatch.
  • System, Configuration shows listeners, the Admin Panel shows dispatched events.

Terms

Autowiring
The container detects dependencies from the types in the constructor.
Decorator
A class that wraps a service and passes its calls on.
Emitter
Code that hands an event to the dispatcher.
Hook
An older extension point that calls registered classes or functions.
Inversion of control
The framework calls your code, not the other way round.
Listener provider
Gives the dispatcher all listeners for an event.
XCLASS
Your own class that TYPO3 creates in place of an original class.

As of: November 15, 2026 (TYPO3 14.3 LTS)

Sources:

  • TYPO3 Explained 14.3, chapters Dependency Injection, Events (PSR-14), Hooks, XCLASS, Symfony Expression Language, Feature Toggles, System Registry
  • PHP-FIG, PSR-11 Container Interface and PSR-14 Event Dispatcher
  • Symfony documentation DependencyInjection (attributes for alias, decorator, tags and environment variables)
  • TYPO3 14.3 source code (typo3/cms-core), checked for AsEventListener, ListenerProviderPass, DataHandler (cache flushing) and ExpressionLanguage
  • Learning objectives TYPO3 CMS Certified Developer 14 LTS, areas core concepts and extensibility

This study guide was written with AI and checked against the sources.

Certifications & exams

Which exam comes next?

You can already practise for 51 exams, and 16 are up for a vote. See all certifications with their official information, cast your vote or suggest your exam.

See all certifications