繁体   English   中英

Symfony2 fos_rest_bundle参数转换器未调用实体构造函数

[英]Symfony2 fos_rest_bundle param converter not calling entity constructor

我正在开发API,并具有以下实体:

/**
 * Solicitud de registro.
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="DnD\RaHApiBundle\Repository\ApplicationRepository")
 */
class Application
{

  public function __construct()
  {
    $pending = new Event("PENDING", "APPLICATION");

    $this->status = new ArrayCollection($pending);
    $this->ownsVehicle = false;
    $this->resident = true;
    $this->timestamp = new DateTime();
  }

  /**
   * @var integer
   *
   * @ORM\Column(name="id", type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="AUTO")
   * @Groups({"application_info"})
   */
  private $id;

  ...

注意构造函数。 它使用其默认值设置我实体中的某些字段。 现在我的控制器的动作:

  /**
   * Crea una nueva solicitud de afiliacion
   * @return array
   *
   * @Post("applications")
   * @ParamConverter("application", converter="fos_rest.request_body")
   */
  public function postAction(Application $application)
  {
    $this->applicationsRepo->save($application);

    // It has no date, no status, no defaults!!!

    $view = $this->view($application, 200);
    $view->getSerializationContext()->setSerializeNull(true);
    $view->getSerializationContext()->setGroups(array('application_info'));
    return $this->viewHandler->handle($view);
  }

$ application对象没有设置默认值,这为什么呢? 如何使转换器调用构造函数并设置所有默认值?

我遇到了同样的问题。 如果您确定不会从请求正文中覆盖默认值,则可以显式调用构造函数。

$application->__construct();

就我而言,我只是想初始化所有ArrayCollection属性,以防止尝试访问它们时出错,因此我不在乎覆盖请求中的标量值。

我也发现

vendor/doctrine/instantiator/src/Doctrine/Instantiator/Instantiator.php

buildFactory方法是问题的根源。 如果您更改:

return $reflectionClass->newInstanceWithoutConstructor();

return $reflectionClass->newInstance();

参数转换器将返回一个对象,该对象的构造函数已被调用。 但是,如果构造函数具有必需的参数,则此操作将失败。 当然,您可以分派教义并更改它,但是这可能会过大:-)

我认为通过将JMS的默认对象构造函数切换到Doctrine,可以调用一个hte实体的构造函数:

services:
  jms_serializer.object_constructor:
    alias: jms_serializer.doctrine_object_constructor
    public: false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM