Property mapping¶
Extbase provides a property mapper to convert different values, like integers or arrays, to other types, like strings or objects.
In this example, we provide a string that will be converted to an integer:
Class T3docs\BlogExample\Controller\PostController¶
class PostController extends \T3docs\BlogExample\Controller\AbstractController
{
/**
* This method demonstrates property mapping to an integer
* @throws \TYPO3\CMS\Extbase\Property\Exception
*/
protected function mapIntegerFromString(string $numberString = '42'): int
{
return $output = $this->propertyMapper->convert($numberString, 'integer');
}
}
Conversion is done by using the TYPO3\CMS\Extbase\Property\PropertyMapper::convert()
method.
Note
The PropertyMapper
has to be injected before it can be used:
Class T3docs\BlogExample\Controller\PostController¶
use T3docs\BlogExample\Domain\Repository\BlogRepository;
use T3docs\BlogExample\Domain\Repository\PersonRepository;
use T3docs\BlogExample\Domain\Repository\PostRepository;
use TYPO3\CMS\Extbase\Property\PropertyMapper;
class PostController extends \T3docs\BlogExample\Controller\AbstractController
{
/**
* PostController constructor.
*
* Takes care of dependency injection
*/
public function __construct(
protected readonly BlogRepository $blogRepository,
protected readonly PersonRepository $personRepository,
protected readonly PostRepository $postRepository,
protected readonly PropertyMapper $propertyMapper
) {
}
}
How to use property mappers¶
This example shows a simple conversion of a string into a model:
Class T3docs\BlogExample\Controller\PostController¶
use T3docs\BlogExample\Domain\Model\Tag;
class PostController extends \T3docs\BlogExample\Controller\AbstractController
{
/**
* This method demonstrates property mapping to an object
* @throws \TYPO3\CMS\Extbase\Property\Exception
*/
protected function mapTagFromString(string $tagString = 'some tag'): Tag
{
$input = [
'name' => $tagString,
];
return $this->propertyMapper->convert(
$input,
Tag::class
);
}
}
The result is a new instance of FriendsOfTYPO3\BlogExample\Domain\Model\Tag
with defined property name
.
Note
The property mapper will not check the validation rules. The result will be whatever the input is.