【问题标题】:Reading annotations with Symfony4使用 Symfony4 阅读注释
【发布时间】:2018-07-20 16:29:39
【问题描述】:

我正在尝试使用 Symfony4 读取注释,但看起来有些东西不起作用!

我要阅读的课程:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\OAuthClientRepository")
 */
class OAuthClient {
{

    /**
     * @Assert\NotBlank()
     * @ORM\Column(type="string")
     */
    protected $name;

}

我用来阅读注释的代码:

<?php

namespace App\Test;

use Doctrine\Common\Annotations\SimpleAnnotationReader as DocReader;

/**
 * Helper AnnotationReader
 */
class AnnotationReader
{

    /**
     * @param $class
     * @return null|\StdClass
     */
    public static function getClass($class)
    {
        $reader = new DocReader;
        $reflector = new \ReflectionClass($class);
        return $reader->getClassAnnotations($reflector);
    }

    /**
     * @param $class
     * @param $property
     * @return array
     */
    public static function getProperty($class, $property)
    {
        $reader = new DocReader;
        $reflector = new \ReflectionProperty($class, $property);
        return $reader->getPropertyAnnotations($reflector);
    }

    /**
     * @param $class
     * @param $method
     * @return array
     */
    public static function getMethod($class, $method)
    {
        $reader = new DocReader;
        $reflector = new \ReflectionMethod($class, $method);
        return $reader->getMethodAnnotations($reflector);
    }

}

当我调用时得到空数组:

App\Test\AnnotationReader::getClass(App\Entity\OAuthClient::class);
App\Test\AnnotationReader::getProperty(App\Entity\OAuthClient::class, 'name');

我做错了什么? 阅读注释的最佳方式是什么?

我正在寻找在类属性上使用的验证。

感谢您的帮助!

【问题讨论】:

    标签: php annotations symfony4


    【解决方案1】:

    改变

    use Doctrine\Common\Annotations\SimpleAnnotationReader as DocReader;
    

    use Doctrine\Common\Annotations\AnnotationReader as DocReader;
    

    它有效。

    【讨论】:

      【解决方案2】:

      您可能必须在 SimpleAnnotationReader 实例上调用 addNamespace() 方法。

      例如,对于 ORM 注释:

      $reader->addNamespace('Doctrine\ORM\Mapping');
      

      对于验证注释:

      $reader->addNamespace('Symfony\Component\Validator\Constraints');
      

      见:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-29
        • 2011-10-08
        • 2023-03-18
        • 2018-10-17
        • 1970-01-01
        • 2016-07-18
        相关资源
        最近更新 更多