For coders TYPO3 Tech Corner

[PHP] Convert array into an extbase object

[PHP] Convert array into an extbase object

public function mapProperties(): AnyModel { $properties = [ 'uid' => 123, 'pid' => 123, 'firstname' => 'Alex', 'lastname' => 'Kellner' 'email' => 'my@email.org' ]; $dataMapper = $this->objectManager->get(TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper::class); $anyModels = $dataMapper->map(AnyModel::class, [$properties]); return $anyModels[0]; } public function mapPropertiesOld(): AnyModel { $properties = [ 'uid' => 123, 'pid' => 123, 'firstname' => 'Alex', 'lastname' => 'Kellner' 'email' => 'my@email.org' ]; $anyModel = $this->objectManager->get(AnyModel::class); $anyModel->setUid($properties['uid'); $anyModel->setPid($properties['pid'); $anyModel->setFirstname($properties['firstname'); $anyModel->setLastname($properties['lastname'); $anyModel->setEmail($properties['email'); return $anyModel; } public function mapManyRecords(): array { $tableName = 'tx_ext_domain_model_table'; $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName); $result = $queryBuilder->select('*')->from($tableName)->setMaxResults(10000)->execute(); $dataMapper = $this->objectManager->get(DataMapper::class); return $dataMapper->map(Table::class, $result->fetchAll()); }

You can also use the PropertyMapper to convert Arrays in Objects, even if the object does not extend AbstractEntity:

$propertyMapper = GeneralUtility::makeInstance(PropertyMapper::class); $object = $propertyMapper->convert($row, Object::class);

Back

"Code faster, look at the time" - does this sound familiar to you?

How about time and respect for code quality? Working in a team? Automated tests?

Join us