1.index.php入口文件实例化 app类(继承contain容器)也是tp主要的核心类
创建app类时初始化路径和绑定类别名最后把实例存储到 $this->instances里
require __DIR__ . '/../vendor/autoload.php';
// 执行HTTP应用并响应
$http = (new App())->http;
$response = $http->run();
$response->send();
$http->end($response);
/**
* 架构方法
* @access public
* @param string $rootPath 应用根目录
*/
public function __construct(string $rootPath = '')
{
$this->thinkPath = realpath(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
$this->rootPath = $rootPath ? rtrim($rootPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : $this->getDefaultRootPath();
$this->appPath = $this->rootPath . 'app' . DIRECTORY_SEPARATOR;
$this->runtimePath = $this->rootPath . 'runtime' . DIRECTORY_SEPARATOR;
if (is_file($this->appPath . 'provider.php')) {
$this->bind(include $this->appPath . 'provider.php');
}
static::setInstance($this); //将自身实例存入$this->instance
$this->instance('app', $this); //将实例化类存入$this->instances 数组里
$this->instance('think\Container', $this);
}
2.调用不存在的http属性触发调用get make()通过反射实例化并返回
/**
* 调用反射执行类的实例化 支持依赖注入
* @access public
* @param string $class 类名
* @param array $vars 参数
* @return mixed
*/
public function invokeClass(string $class, array $vars = [])
{
try {
$reflect = new ReflectionClass($class);
} catch (ReflectionException $e) {
throw new ClassNotFoundException('class not exists: ' . $class, $class, $e);
}
if ($reflect->hasMethod('__make')) { //判断make方法是否存在 和构造函数差不多
$method = $reflect->getMethod('__make'); //获取make方法的信息
if ($method->isPublic() && $method->isStatic()) {
$args = $this->bindParams($method, $vars);
$object = $method->invokeArgs(null, $args); //调用反射类方法返回值
$this->invokeAfter($class, $object);
return $object;
}
}
$constructor = $reflect->getConstructor(); //获取构造函数的信息(参数类型和参数列表)
$args = $constructor ? $this->bindParams($constructor, $vars) : [];
$object = $reflect->newInstanceArgs($args); //实例化类 返回类
$this->invokeAfter($class, $object);
return $object;
}
3.tp6 通过自定义static __make函数实现实例化返回实例化类没有__make则是通过构造函数