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

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

阅读 6.5k
3 个回答

一、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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题