首页 > symfony的annotations功能是在哪儿实现的?

symfony的annotations功能是在哪儿实现的?

symfony的annotations功能(路由、数据验证、ORM等地方用到的)是在哪儿实现的?
我问的是代码在哪儿,不是如何实现的。实现方式我估计是分析tokens以及php的反射api。是用的doctrine的annotations组件实现的么?


annotation直接实现在(或者说常用annotation定义在)这个bundle里:
https://symfony.com/doc/master/bundles/SensioFrameworkExtraBundle/index.html
不过这个bundle有Doctrine\Common依赖:
https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/master/composer.json
所以八九不离十,底层是Doctrine的系统,没有理由用了Doctrine还自己去实现一遍的。
另一个依赖是Framework Core,本身是不带Annotation支持的。


建议不要太依赖annotation 效率会有一定影响不是很高的


一、Symfony的annotation的实现使用了该组件Doctrine\Common\Annotations

1.每一个annotation都有一个相对应的类

1)以Route[1]为例,如下,其是[2]的一个子类:

[1]Sensio\Bundle\FrameworkExtraBundle\Configration\Route
[2]Symfony\Component\Routing\Annotation\Route

2)其他,比如Method[3],Security[4]等均[5]的子类

[3]Sensio\Bundle\FrameworkExtraBundle\Configuration\Method
[4]Sensio\Bundle\FrameworkExtraBundle\Configuration\Security
[5]Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationAnnotation

2.通过运行如下图中的命令发现,Symfony框架与annotation相关的服务只有一个 - "annotation_reader"

Symfony通过这一服务,其实是"Doctrine\Common\Annotations\CachedReader",把每个annotation转换为annotation类(对象),然后再获取相应的各个参数,进行处理

比如,Route相对应的有一个类是"Symfony\Component\Routing\Loader\AnnotationClassLoader",这个类的load方法通过使用"annotation_reader"和PHP的反射API(ReflectionClass)对控制器对象和annotation类(Route)进行处理,最终返回RouteCollection对象

3.如上所述,实现方式的确用到了PHP的反射API(参考"Symfony\Component\Routing\Loader\AnnotationClassLoader")

4.通过使用"annotation_reader"这一服务和PHP的反射API(ReflectionClass),开发者甚至可以自己写自己的annotation类和ClassLoader,这里有一篇国外的文章专门讲这个(虽然是几年前的,但是内容没有过时)

Symfony2 & Doctrine Common: creating powerful annotations

【热门文章】
【热门文章】