TP5.1 源码窥探之反射和 Yaconf 配置扩展
在解读TP源码之前我们首先了解一下,什么是反射,什么是Yaconf配置,什么是Yaml配置,甚至一些常见的设计模式,比如单例模式,简单工厂模式,注册树模式等。
反射
官方的解释:PHP 5 具有完整的反射 API,添加了对类、接口、函数、方法和扩展进行反向工程的能力。 此外,反射 API 提供了方法来取出函数、类和方法中的文档注释。它不需要其他扩展,是PHP核心的一部分。我们平常在面向对象开发的时候,经常使用到类,接口,方法等。而类是有属性和方法组成的,利用PHP的反射机制,我们可以读取类,接口,方法,属性的信息。
举个例子,一目了然
include 'note/Obj.php';
$class = Obj::class;
$reflectionClass = new \ReflectionClass($class);
//检查一个类中指定的方法是否已定义
$hasMethod = $reflectionClass->hasMethod('buy');
//类报告了一个方法的有关信息
$method = new ReflectionMethod($class,'buy');
//判断方法是否是公共方法
$methodIsPublic = $method->isPublic();
//判断方法是否是受保护方法
$methodIsProtected = $method->isProtected();
//判断方法是否是私有方法
$methodIsPrivate = $method->isPrivate();
//判断方法是否是静态方法
$methodIsStatic = $method->isStatic();
//获取方法的注释
$methodDocument = $method->getDocComment();
$methodNumOfParameters = $method->getNumberOfParameters();
$methodNumOfRequiredParameters = $method->getNumberOfRequiredParameters();
//返回 ReflectionParameter 数组
$methodParameters = $method->getParameters();
$args = [];
if($methodNumOfParameters){
foreach($methodParameters as $methodParameter){
//获取参数名
$parameterName = $methodParameter->getName();
//获取参数的类型提示类,类型为ReflectionClass对象
$class = $methodParameter->getClass();
//检查参数是否有默认值
$isDefaultValueAvailable = $methodParameter->isDefaultValueAvailable();
if($isDefaultValueAvailable){
$defaultValue = $methodParameter->getDefaultValue();
$args[] = $defaultValue;
}else{
$args[] = '大奔';
}
}
}
if($methodIsPublic && $methodIsStatic){
//使用数组给方法传送参数,并执行他
$res = $method->invokeArgs(null,$args);
}
//一个 ReflectionMethod 对象,反射了类的构造函数,或者当类不存在构造函数时返回 NULL。
$construct = $reflectionClass->getConstructor();
$args = $construct ? [30] : [];
//实例化一个Obj对象
$newObj = $reflectionClass->newInstanceArgs($args);
配置
我们平常项目开发配置文件的类型,要么是env文件,php文件,json文件,ini文件,txt文件等,今天介绍两个配置,一个是Yaconf,另外一个是Yaml
安装yaconf和yaml扩展
你也可以在[PECL]中直接安装,以及下载windows下的dll。yaconf要求php7才能用。另外windows安装扩展的时候,echo pathinfo()
查看是否是nts或者ts,同时注意系统是32位还是64位。
配置
在php.ini中添加此两个扩展。同时配置yaconf目录yaconf.directory
和yaconf.check_delay
。不要忘记重启PHP。
extension=php_yaml.dll
extension=php_yaconf.dll
yaconf.directory="D:\xxx\xxx\www\tp5\yaconf"
yaconf.check_delay=0
举例
yaconf.ini
name="bar"
person.name='张三'
person.sex='男'
arr[]=1
arr[]=2
[estate]
location = '郑州'
price=118
[children:estate]
price=5210
son=18
yaml.yaml
animal: pets
hash: { name: Steve, foo: bar }
animals:
- Cat
- Dog
- Goldfish
#数值数组
languages:
- Ruby
- Perl
- Python
#关联数组
websites:
YAML: yaml.org
Ruby: ruby-lang.org
Python: python.org
Perl: use.perl.org
index.php
if(class_exists('Yaconf')){
$res = Yaconf::get('yaconf.name');//yaconf对应yaconf.ini文件
$res = Yaconf::get('yaconf.arr');
$res = Yaconf::get('yaconf.person');
$res = Yaconf::get('yaconf.person.name');
$res = Yaconf::get('yaconf.estate');
$res = Yaconf::get('yaconf.children');
var_dump($res);
}
$file = 'yaml.yaml';
if( function_exists('yaml_parse_file') ){
$config =yaml_parse_file($file);
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: