【问题标题】:PHP find variable type from property through annotationPHP通过注解从属性中查找变量类型
【发布时间】:2016-04-15 09:44:08
【问题描述】:

我使用 Symfony 3 从现有项目开发 Web 应用程序已有 8 年多的时间了。 因此,我继承了现有模型。

有些实体有这个字段

/**
 * @var integer
 *
 * @ORM\Column(name="FourID_Site", type="bigint", nullable=true)
 */
private $fouridSite;

还有一些人有

/**
 * @var \FourListe
 *
 * @ORM\ManyToOne(targetEntity="FourListe")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="FourID_Site", referencedColumnName="FourID")
 * })
 */
private $fouridSite;

我有一个在所有持久化和刷新原则方法之前调用的方法,用于自动更新某些字段。

    if (property_exists(get_class($entity), 'fouridSite')) {
        $entity->setFouridSite($this->current_user->getFouridSiteutilisateur());
    }
    if (property_exists(get_class($entity), 'majlogin')) {
        $entity->setMajlogin($this->current_user->getLogin());
    }
    if (property_exists(get_class($entity), 'majdate')) {
        $entity->setMajdate(new \DateTime());
    }

问题:$fouridSiteinteger 时,此代码会引发错误,因为我无法分配实体 ( $this->current_user->getFouridSiteutilisateur() 返回一个 FourListe 实体) 当学说需要一个整数时。而且很正常。

在这种情况下不能使用原生 php 方法 get type(),因为它返回 NULL。

https://php.net/gettype

那么,也许有一种方法可以通过注解来知道$fourisSite 是一个实体还是一个整数?

感谢您的想法或潜在的任何建议?

【问题讨论】:

    标签: php symfony doctrine-orm annotations


    【解决方案1】:

    根据更新挂钩的位置,您可以使用它来了解列的类型:

    $em = $this->get('doctrine')->getManager();
    $metadata = $em->getClassMetadata(get_class($entity));
    $fieldMetadata = $metadata->fieldMappings['fouridSite'];
    
    // Catch the type
    $fieldType = $fieldMetadata['type'];
    

    然后对该类型添加一些检查以注册良好的价值。
    希望您可以通过您的方法访问学说服务。

    【讨论】:

      猜你喜欢
      • 2013-02-10
      • 2021-01-07
      • 2013-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      相关资源
      最近更新 更多