doufu2496 2015-04-30 19:17
浏览 33
已采纳

Symfony2 fos_rest_bundle param转换器不调用实体构造函数

I'm developing an API and have the following entity:

/**
 * 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;

  ...

Notice the constructor. It sets some fields in my entity with their default values. Now my controller's action:

  /**
   * 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);
  }

The $application object doesn't have its default values set, why is this? how can I make the converter call the constructor and set all default values?

  • 写回答

1条回答 默认 最新

  • drlhsfqoa350437979 2015-05-18 17:29
    关注

    I ran into the same problem. If you're sure that the default values won't be overwritten from the request body you can call the constructor explicitly.

    $application->__construct();
    

    In my case I just wanted to initialize all the ArrayCollection properties to prevent errors trying to access them so I didn't care about overwriting scalar values from the request.

    I've also found that in

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

    the buildFactory method is the source of the problem there. If you change:

    return $reflectionClass->newInstanceWithoutConstructor();

    to

    return $reflectionClass->newInstance();

    the param converter will return an Object whose constructor has been called. However this will fail if the constructor has required arguments. Of course you could fork doctrine and change this, but it might be overkill :-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条