PSR-14 events
Target group: Developers
Table of Contents
Introduction
You can enhance the functionality in the schema extension with PSR-14 event listeners. An event listener receives an event that provides methods for retrieving and setting dedicated properties.
See also
You can find more information about PSR-14 events in the blog article PSR-14 Events in TYPO3 and the official TYPO3 documentation.
Render additional types
The event allows to add markup in cases where no controller is available, for example, if you want to enrich a page with structured data depending on the doktype of a page.
The event
\Brotkrueml\
provides the following methods:
- getRequest(): \Psr\Http\Message\ServerRequestInterface
-
Returns the PSR-7 request object.
- addType(TypeInterface ...$type): void
-
Add one or more type models.
- addMainEntityOfWebPage(TypeInterface $mainEntity): void
-
Add a main entity.
Example
In the following example we add structured data markup depending on the doktype of the page:
<?php
declare(strict_types=1);
namespace MyVendor\MyExtension\EventListener;
use Brotkrueml\Schema\Event\RenderAdditionalTypesEvent;
use Brotkrueml\Schema\Type\TypeFactory;
use TYPO3\CMS\Core\Attribute\AsEventListener;
use TYPO3\CMS\Frontend\Page\PageInformation;
#[AsEventListener(
identifier: 'my-extension/add-markup-to-article-pages',
)]
final readonly class AddMarkupToArticlePages
{
public function __construct(
private TypeFactory $typeFactory,
) {}
public function __invoke(RenderAdditionalTypesEvent $event): void
{
// The "frontend.page.information" attribute is available since TYPO3 v13.
// Use the "frontend.controller" attribute (TSFE) in older TYPO3 versions
// to retrieve the page record.
/** @var PageInformation $pageInformation */
$pageInformation = $event->getRequest()->getAttribute('frontend.page.information');
$page = $pageInformation->getPageRecord();
if ($page['doktype'] !== 12345) {
return;
}
// Only for doktype 12345
$article = $this->typeFactory->create('Article');
$article->setProperty('name', $page['title']);
// ... and set some other properties
$event->addType($article);
}
}
The method
__
implements the logic for rendering additional
types. It receives the
Render
. You can add as many
types as you like.