首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Symfony4读取注释

使用Symfony4读取注释
EN

Stack Overflow用户
提问于 2018-07-21 00:29:39
回答 2查看 3.8K关注 0票数 2

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

我尝试从下面的类中读取:

代码语言:javascript
复制
<?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;

}

我用来读取注释的代码如下:

代码语言:javascript
复制
<?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);
    }

}

当我调用以下命令时,会得到空数组:

代码语言:javascript
复制
App\Test\AnnotationReader::getClass(App\Entity\OAuthClient::class);
App\Test\AnnotationReader::getProperty(App\Entity\OAuthClient::class, 'name');

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

我希望读取在类属性上使用的验证。

谢谢你的帮助!

EN

回答 2

Stack Overflow用户

发布于 2018-10-03 16:14:23

变化

代码语言:javascript
复制
use Doctrine\Common\Annotations\SimpleAnnotationReader as DocReader;

代码语言:javascript
复制
use Doctrine\Common\Annotations\AnnotationReader as DocReader;

这就是工作

票数 1
EN

Stack Overflow用户

发布于 2018-07-22 05:12:36

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

例如,对于ORM注释:

代码语言:javascript
复制
$reader->addNamespace('Doctrine\ORM\Mapping');

而对于验证注解:

代码语言:javascript
复制
$reader->addNamespace('Symfony\Component\Validator\Constraints');

请参见:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51446869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档