duandu5846 2018-07-20 16:29
浏览 103

使用Symfony4读取注释

I'm trying to read annotations with Symfony4 but looks like something is not working!

The class I'm trying to read from:

<?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;

}

The code I'm using to read the annotations:

<?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);
    }

}

I get empty arrays when I call:

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

What am I doing wrong? What is the best way to read annotation?

I'm looking to read the validations used on a class property.

Thank you for your help!

  • 写回答

2条回答 默认 最新

报告相同问题?