Entity to Datamap/Array

流过昼夜 提交于 2019-12-02 11:50:44

问题


I have an Entity like that:

class Company extends AbstractEntity
{
  /**
   * @var string
   */
  protected $longName = '';

  //much more properties

  //all the setters and getters
}

I would like to use the DataHandler from the typo3 core to save such an Entity, because saving the entity should trigger the whole workspace mechanics, such that the updated Object/Entity/row is created as a new version. Extbase directly writes to the Database, what bypasses that.

Basically one can use the api like so:

$data = [
  'long_name' => 'some very long Name'
];

$cmd = [];
$cmd['tablename_for_entity']['uid_of_entity'] = $data;

$dataHandler->start($cmd, []);
$dataHandler->process_datamap();

So the Problem is to turn the Entity into a »DataMap« or appropriate array.

How can I do that?


回答1:


The reason for such a thing is a kind of a hack/workaround, to use the workspaces functionality from the frontend. That bypasses the database abstraction layer, which is very nice to have, just to trigger some hooks. I hope that this wont be needed in future releases but for now, I could solve it with this solution:

public function map(AbstractEntity $entity):array
{
  $result = [];

  $class = get_class($entity);

  /** @var ClassReflection $reflection */
  $reflection = GeneralUtility::makeInstance(ClassReflection::class, $class);

  /** @var DataMapper $mapper */
  $mapper = GeneralUtility::makeInstance(DataMapper::class);

  $dataMap = $mapper->getDataMap($class);

  foreach ($entity->_getProperties() as $property => $value) {
    $colMap = $dataMap->getColumnMap($property);
    $reflProp = $reflection->getProperty($property);

    if (!is_null($colMap) and $reflProp->isTaggedWith('maptce')) {
      $result[$colMap->getColumnName()] = $mapper->getPlainValue($value, $colMap);
    }
  }

  return $result;
}

That basically does something like \TYPO3\CMS\Extbase\Persistence\Generic\Backend::persistObject() and most of the code is taken from there as well. But the general Data mapping especially for nested Entities and so on is would have been too complex for now, so I decided to just test if a property has an @maptce annotation to simplify the process.

It is no Problem to skip some properties since the TCE process_datamap() method will care about that.



来源:https://stackoverflow.com/questions/51395532/entity-to-datamap-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!