Study guide · Extbase: MVC, Plugins and Views
Understanding Extbase: From the request to the finished output
Extbase is the tool in TYPO3 for building extensions with their own domain model, such as events, products or job postings. On this page you follow a single request through Extbase: from the URL through controller and view to the finished HTML. Along the way you learn how to register plugins, how caching decides and what happens when something goes wrong.
What is Extbase?
Extbase is a framework in the TYPO3 Core. It splits the code according to the Model-View-Controller pattern, MVC for short:
- The model describes your data, for example a conference with a title and a date.
- The controller receives the request and decides what happens.
- The view turns the data into output, usually HTML.
Extbase also ships an Object-Relational Mapper. So you work with PHP objects instead of SQL. The template engine is called Fluid. Extbase uses Fluid as its view, but Fluid is a separate package and not Extbase itself.
The example on this page
All examples belong to an extension with the key my_extension. It has a model Conference, a ConferenceController with the actions list, show, new and create, and a plugin ConferenceList. The files live in fixed places:
- The controller is
ConferenceController.phpin the folderClasses/Controller. - The model is
Conference.phpin the folderClasses/Domain/Model. The folderClasses/Domain/Repositoryholds the repositories. - The folders
Templates,LayoutsandPartialsinResources/Privatehold the Fluid files. The folderResources/Private/Languageholds the translations. - The files
ext_localconf.phpandtt_content.phpinConfiguration/TCA/Overridesregister the plugin.
The model Conference extends AbstractEntity and is identified by its uid. Since TYPO3 14 you write value objects without their own identity as plain PHP classes, because AbstractValueObject is now internal only. How models are stored and loaded is covered in the course “Extbase: Persistenz und Validierung”.
The path of a request
Extbase does not receive the whole URL like a standalone framework. First, TYPO3 looks for the matching page in the page tree. Extbase only takes over when TYPO3 renders the content elements of this page and comes across a plugin. So a plugin is a small application inside a page. That is why several plugins can sit on the same page.
So that plugins do not get in each other's way, their URL arguments have their own plugin namespace. It is made of tx, an underscore, the extension key without underscores, another underscore and the plugin name, all lowercase. For our plugin that gives the namespace tx_myextension_conferencelist:
?tx_myextension_conferencelist[action]=show&tx_myextension_conferencelist[conference]=42Readable URLs without these brackets only come from a route enhancer in the site configuration. Extbase itself does not build readable URLs.
If two plugins should read the same arguments, for example a filter and a list, you give both the same namespace with view.pluginNamespace.
Controllers and actions
A controller extends ActionController. Every public method whose name ends in Action is an action. So the action list in the URL leads to a call of listAction(). A method list() without the suffix is never called as an action.
Every action must return a ResponseInterface. Usually that is the result of the controller method htmlResponse(). Without an argument it renders the template that belongs to the action.
public function listAction(): ResponseInterface
{
$this->view->assign('conferences', $this->conferenceRepository->findAll());
return $this->htmlResponse();
}Before the action, Extbase calls preparatory methods in a fixed order. First comes initializeAction() for all actions. Then comes initializeShowAction(), only before showAction(). Then the arguments are converted. Then initializeView() runs, and finally the action itself. In initializeCreateAction(), for example, you set the format in which a date arrives from the form.
Arguments reach the action through its parameters. For a showAction() with a Conference parameter, Extbase loads the object with the UID from the URL by itself. Optional parameters need a default value. Alternatively, you ask the request directly with hasArgument() and getArgument().
public function listAction(int $currentPage = 1): ResponseInterface
if ($this->request->hasArgument('currentPage')) {
$page = $this->request->getArgument('currentPage');
}More data is found in two places. The request property of the controller holds a PSR-7 request. From it you read attributes with getAttribute(), such as the logged-in frontend user under the name frontend.user. Controller and action name are stored in the attribute extbase. The settings property holds the settings from TypoScript and the FlexForm. Values from TypoScript arrive there as strings. If you set itemsPerPage to 10 in TypoScript, the controller receives the string 10, not a number.
Responses, redirect and forward
Not every action returns an HTML page:
- The method
jsonResponse()outputs JSON, either through the JsonView or with a ready-made JSON string as its argument. - If you call
withStatus()with 404 on the result ofhtmlResponse(), the template is rendered, but the status 404 is sent. In the same way,withHeader()adds your own headers. - After saving,
addFlashMessage()shows a message. In the template, the ViewHelperf:flashMessagesoutputs it. You choose the severity withContextualFeedbackSeverity, for exampleWARNING. - You take the text of the flash message from the
locallang.xlffile withLocalizationUtility::translate(), passing the key and the extension name. - The
uriBuilderbuilds an absolute URL, for example for a confirmation email. The code block below shows how.
$text = LocalizationUtility::translate('flash.saved', 'MyExtension');
$url = $this->uriBuilder->reset()->setCreateAbsoluteUri(true)->uriFor('show', ['conference' => $conference]);After a form you usually want to switch to another action. There are two ways to do this, and they differ clearly.
- Redirect: The method
redirect()sends the status 303 to the browser. The browser then loads the new page. If someone reloads that page, the form is not submitted again, and no duplicate record is created. - Forward: Returning a new
ForwardResponsehands the work to another action within the same request. The URL stays the same, and you cannot name a different target page with it.
return $this->redirect('show', null, null, ['conference' => $conference]);
return new ForwardResponse('new');The view: Fluid
The controller passes data with the view method assign(), or several values at once with assignMultiple(). In the template they are then available under their name, for example as the variable conferences. Settings are available as settings.itemsPerPage.
Which template? Extbase derives the file name from controller and action. For the showAction() of the ConferenceController, that is the file Show.fluid.html in the folder Templates/Conference below Resources/Private. The extension fluid.html is common since TYPO3 14, and old files ending in html keep working. For a different format such as JSON, Fluid looks for Show.fluid.json.
Overriding templates: The paths are kept in three lists, templateRootPaths, layoutRootPaths and partialRootPaths. Each entry has a number as its key. The highest key is searched first. The default path of the extension has the lowest priority.
Layouts and partials: A layout is the frame around the template. It renders the section Main, which the template provides. A partial is a reusable piece, for example a card for a conference. It only sees the variables you pass to it with arguments. The special value _all passes everything.
<f:render section="Main" />
<f:section name="Main">
<f:render partial="ConferenceItem" arguments="{conference: conference}" />
</f:section>
<f:render partial="ConferenceItem" arguments="{_all}" />When conference.title stays empty: Fluid looks for a public property or a getter such as getTitle(). If it finds neither, it silently outputs an empty string, without an error message. Typical causes are a typo in the variable name, a missing getter or a partial without arguments.
CSS and JavaScript: The sections HeaderAssets and FooterAssets are deprecated since TYPO3 14 and will be removed in version 15. Use the ViewHelpers f:page.headerData and f:page.footerData instead.
Links and forms: The ViewHelper f:link.action links to an action. If the detail view is on another page in another plugin, you add pageUid and pluginName. A form for a createAction() with the parameter newConference starts with the ViewHelper f:form. Its name and object match that parameter. You bind the fields with the attribute property.
<f:link.action action="show" arguments="{conference: conference}">Details</f:link.action>
<f:form action="create" name="newConference" object="{newConference}">
<f:form.textfield property="title" />
</f:form>JSON instead of HTML: If a controller sets its property defaultViewObjectName to the JsonView class, all of its actions return JSON. With setVariablesToRender() you choose the variables. Without this call, the JsonView only outputs the variable value. A custom view class that is not a JsonView is rejected by Extbase at this point with a RuntimeException. With setConfiguration() and the keys _only, _exclude, _descend and _descendAll you decide which properties end up in the JSON.
protected ?string $defaultViewObjectName = JsonView::class;Registering plugins
An Extbase plugin needs two calls with exactly the same extension and plugin name:
ExtensionUtility::configurePlugin()inext_localconf.phpconnects the plugin to controllers and actions. The first action of the first controller is the default action. The fourth parameter lists the actions that must not be cached.ExtensionUtility::registerPlugin()in the TCA override file fortt_contentmakes the plugin selectable in the backend, with title, icon, group, description and FlexForm.
ExtensionUtility::configurePlugin(
'MyExtension',
'ConferenceList',
[ConferenceController::class => 'list, show, new, create'],
[ConferenceController::class => 'new, create'],
);Since TYPO3 14, every plugin is a content element of its own with its own CType. The old “General Plugin” with list_type no longer exists. The CType is named after the plugin signature. That is the extension name without underscores, an underscore and the plugin name, all lowercase, at most 32 characters. For us that is myextension_conferencelist. You pass a FlexForm to registerPlugin() as a path with the prefix FILE:.
Where do the settings come from? Extbase merges the configuration in a fixed order, and later sources win. First comes config.tx_extbase. Then comes plugin.tx_myextension for all plugins of the extension. Then comes plugin.tx_myextension_conferencelist for this plugin, and finally the FlexForm. An empty FlexForm field overrides the TypoScript value. If you add the field to ignoreFlexFormSettingsIfEmpty, the TypoScript value is kept.
Without Extbase a plugin works too. TypoScript calls a PHP method with userFunc, either as USER, which is cached, or as USER_INT, which is not cached. Since TYPO3 14 this method needs the attribute AsAllowedCallable. You register it as a content element with ExtensionManagementUtility::addPlugin().
Caching: cached or not?
Normally the output of a plugin ends up in the page cache. The next visitor gets it ready-made, without your controller running again. That is fast, but it does not suit everything.
An action should only be non-cacheable if its output must not be shared. Examples are forms with a fresh security token, content per logged-in user, or live data. For this, an action must be listed in the third and in the fourth parameter.
EXTBASEPLUGIN: With this TypoScript object you can output an Extbase plugin without a content element, for example a shopping cart in the header of every page. configurePlugin() itself creates exactly such an object for the content element.
lib.conferenceList = EXTBASEPLUGIN
lib.conferenceList {
extensionName = MyExtension
pluginName = ConferenceList
}The same caching rule applies here. The object starts as a cached USER. If the called action is not cacheable, it becomes USER_INT. Responses with a status of 300 or higher, such as redirects, are never stored in the cache.
When something goes wrong
Invalid form data: If converting or validating the arguments fails, Extbase calls the built-in errorAction() instead of the action. It does three things:
- It adds an error message whose text comes from
getErrorFlashMessage(). - It forwards back to the action that showed the form.
- It sets the status 400.
Since TYPO3 14, the errorAction() no longer stores this message in the session. Otherwise crawlers would have created masses of needless sessions. If you want no message at all, you override getErrorFlashMessage() and return false. For full control, you override errorAction() yourself.
Record not found: If someone calls showAction() with the UID of a deleted record, Extbase throws a TargetNotFoundException. The errorAction() does not apply here. If you set the TypoScript option shown below to 1, TYPO3 shows the 404 page instead. If you need something else, for example a log entry and a redirect, you override handleArgumentMappingExceptions() in the controller.
config.tx_extbase.mvc.showPageNotFoundIfTargetNotFoundException = 1
plugin.tx_myextension_conferencelist.mvc.showPageNotFoundIfTargetNotFoundException = 1Key points
- Extbase only takes over when TYPO3 renders a plugin on the page.
- Actions end in Action and always return a
ResponseInterface. - A redirect sends status 303 and makes the browser start a new request. A forward stays in the same request with the same URL.
- Templates live in the folder
Templates, in a subfolder named after the controller, in a file named after the action with the extension fluid.html. - The highest template path key is searched first.
- Partials only see what you pass to them with
arguments. - A plugin needs
configurePlugin()andregisterPlugin()with identical names, and since version 14 it is aCTypeof its own. - The called action decides whether output is cached. An action in the fourth parameter makes the plugin
USER_INT. errorAction()handles invalid arguments, not missing records.
Terms
- Action
- Public controller method whose name ends in Action.
- Dispatcher
- Picks the controller and calls it, and also processes forwards.
- Flash message
- Short message that is shown once after an action.
- Plugin namespace
- Prefix of a plugin's URL arguments, for example tx_myextension_conferencelist.
- Plugin signature
- Extension name without underscores plus plugin name, in lowercase, which gives the CType.
- PSR-7
- PHP standard for request and response objects.
- USER and USER_INT
- Cached and uncached TypoScript object.