我可以使用 Doctrine\Common\Annotations\AnnotationReader
类在 Symfony 中读取自定义注释。
它看起来像下面。我已经描述了属性:
/**
* @var array
* @MappingClient(ignore=true)
*/
protected static $myProperty = [];
我可以解析注解@MappingClient
:
$class = new \ReflectionClass(get_called_class());
$property = $class->getProperty('myProperty');
$annotationReader = new AnnotationReader();
$mappingClient = $annotationReader
->getPropertyAnnotation($property, 'MyClass\Annotation\MappingClient');
我还需要解析属性类型,如@var array
中所述。我明白我可以在 $property->getDocComment()
上用正则表达式解析它。但是,如果 getPropertyAnnotation()
忽略 @var
和其他标准声明,我怎么可能只使用 Symfony 类呢?有没有更优雅的方式?
最佳答案
如果您使用 Symfony 2.8 或 Symfony 3,您可以使用 the PropertyInfo component .它正是这样做的。
在 Controller 中:
$this->get('property_info')->getTypes('FooClass', 'foo'); // Must be enabled in the framework configuration
// array(1) {
// [0] =>
// class Symfony\Component\PropertyInfo\Type#36 (6) {
// private $builtinType => string(6) "object"
// private $nullable => bool(false)
// private $class => string(8) "DateTime"
// private $collection => bool(false)
// private $collectionKeyType => NULL
// private $collectionValueType => NULL
// }
// }
关于php - 如何在 Symfony 中解析 phpdoc 属性类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34339339/