简体   繁体   English

使用 Symfony4 阅读注释

[英]Reading annotations with Symfony4

I'm trying to read annotations with Symfony4 but looks like something is not working!我正在尝试使用 Symfony4 阅读注释,但看起来有些东西不起作用!

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!谢谢您的帮助!

change改变

use Doctrine\Common\Annotations\SimpleAnnotationReader as DocReader;

to

use Doctrine\Common\Annotations\AnnotationReader as DocReader;

and it works.它有效。

You may have to call the addNamespace() method on the SimpleAnnotationReader instance.您可能必须在SimpleAnnotationReader实例上调用addNamespace()方法。

For instance, for ORM annotations:例如,对于 ORM 注释:

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

And for validation annotations:对于验证注释:

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

See:看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM