doufu2496 2015-04-30 11: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 09: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 :-)

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部