一、概念:
1. 为什么要使用注解?
①. PHP是没有注解,所以只能用注释来模拟.
②. 借鉴了Java spring的思想.
③. 一般框架会使用Doctrine Annotations库:
https://github.com/doctrine/annotations
④. swoole是常驻内存的,使用IoC容器结合注解特别有意义.
1.1 反射实现注解原理:
PHP中利用反射(getDocComment)来读取类或方法上的注释内容(一堆字符串),再正则或其它方式解析出"有规则的内容".
①. 获取文档注释:
public ReflectionClass::getDocComment(void): string
②. 举例:
/**
* This is an Example class
*/
class Example
{
/**
* This is an example function
*/
public function fn() {}
}
$reflector = new ReflectionClass('Example');
echo $reflector->getDocComment(); # // to get the Class DocBlock
$reflector->getMethod('fn')->getDocComment(); # // to get the Method DocBlock
1.2 注解最基本的作用 - “扫描器”:
①. 扫描的意思是循环读取指定的文件夹下面的文件.
②. 没有注解需要在文件名上区分,指定哪些文件夹可以加载,哪些文件夹不可以加载.
③. 有了注解:
a. 就可以不用在文件名上区分,用这个第三方库来分析注解,是否符合要求即可.
b. 有了注解之后,就可以决定哪些类扫进去(就是加载required指定文件).