【问题标题】:Symfony2 fos_rest_bundle param converter not calling entity constructorSymfony2 fos_rest_bundle 参数转换器不调用实体构造函数
【发布时间】:2015-04-30 19:17:58
【问题描述】:

我正在开发一个 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 对象没有设置默认值,这是为什么呢?如何让转换器调用构造函数并设置所有默认值?

【问题讨论】:

    标签: php symfony converter fosrestbundle


    【解决方案1】:

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

    $application->__construct();
    

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

    我也发现了

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

    buildFactory 方法是问题的根源。如果你改变:

    return $reflectionClass->newInstanceWithoutConstructor();

    return $reflectionClass->newInstance();

    参数转换器将返回一个其构造函数已被调用的对象。但是,如果构造函数具有必需的参数,这将失败。当然你可以分叉学说并改变它,但这可能是矫枉过正:-)

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-06
        • 2012-10-21
        • 1970-01-01
        相关资源
        最近更新 更多