一、入口概述
public/index.php
$http = (new App())->setEnvName('local')->http;
$response = $http->run();
$response->send();
$http->end($response);
1.1 创建容器
1.1.1、创建预加载器
Laminas\ZendFrameworkBridge\Autoloader
createPrependAutoloader(){}
通过 Composer\Autoload\ClassLoader 去加载对应文件
loadClass(){}
1.1.2、绑定容器
think\app 初始化框架基础,加载app目录下的 provider文件,绑定到app容器,并初始化成单里
其中 think\app 类继承了 think\container 容器类
class App extends Container
{
protected $appPath = '';
protected $runtimePath = '';
protected $routePath = '';
protected $initializers = [
Error::class,
RegisterService::class,
BootService::class,
];
protected $services = [];
protected $initialized = false;
protected $bind = [
'app' => App::class,
'cache' => Cache::class,
'config' => Config::class,
'console' => Console::class,
'cookie' => Cookie::class,
'db' => Db::class,
'env' => Env::class,
'event' => Event::class,
'http' => Http::class,
'lang' => Lang::class,
'log' => Log::class,
'middleware' => Middleware::class,
'request' => Request::class,
'response' => Response::class,
'route' => Route::class,
'session' => Session::class,
'validate' => Validate::class,
'view' => View::class,
'filesystem' => Filesystem::class,
'think\DbManager' => Db::class,
'think\LogManager' => Log::class,
'think\CacheManager' => Cache::class,
'Psr\Log\LoggerInterface' => Log::class,
];
public function __construct(string $rootPath = '')
{
$this->thinkPath = 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('app', $this);
$this->instance('think\Container', $this);
}
public function register($service, bool $force = false){
}
public function instance(string $abstract, $instance)
{
$abstract = $this->getAlias($abstract);
$this->instances[$abstract] = $instance;
return $this;
}
}
1.2 设置环境
think\App.php
public function setEnvName(string $name)
{
$this->envName = $name;
return $this;
}
1.3 获取http服务
$http = (new App())->setEnvName()->http;
1.4 执行请求
$response = $http->send();
1.5 执行结束时的工作
$http->end($response);
二、创建容器
2.1 think\Container.php 源码分析
<?php
namespace think;
use ArrayAccess;
use ArrayIterator;
use Closure;
use Countable;
use InvalidArgumentException;
use IteratorAggregate;
use Psr\Container\ContainerInterface;
use ReflectionClass;
use ReflectionException;
use ReflectionFunction;
use ReflectionFunctionAbstract;
use ReflectionMethod;
use think\exception\ClassNotFoundException;
use think\exception\FuncNotFoundException;
use think\helper\Str;
class Container implements ContainerInterface, ArrayAccess, IteratorAggregate, Countable {
protected static $instance;
protected $instances = [];
protected $bind = [];
protected $invokeCallback = [];
public static function getInstance() {
if (is_null(static::$instance)) {
static::$instance = new static;
}
if (static::$instance instanceof Closure) {
return (static::$instance)();
}
return static::$instance;
}
public static function setInstance($instance): void {
static::$instance = $instance;
}
public function resolving($abstract, Closure $callback = null): void {
if ($abstract instanceof Closure) {
$this->invokeCallback['*'][] = $abstract;
return;
}
$abstract = $this->getAlias($abstract);
$this->invokeCallback[$abstract][] = $callback;
}
public static function pull(string $abstract, array $vars = [], bool $newInstance = false) {
return static::getInstance()->make($abstract, $vars, $newInstance);
}
public function get($abstract) {
if ($this->has($abstract)) {
return $this->make($abstract);
}
throw new ClassNotFoundException('class not exists: ' . $abstract, $abstract);
}
public function bind($abstract, $concrete = null) {
if (is_array($abstract)) {
foreach ($abstract as $key => $val) {
$this->bind($key, $val);
}
} elseif ($concrete instanceof Closure) {
$this->bind[$abstract] = $concrete;
} elseif (is_object($concrete)) {
$this->instance($abstract, $concrete);
} else {
$abstract = $this->getAlias($abstract);
if ($abstract != $concrete) {
$this->bind[$abstract] = $concrete;
}
}
return $this;
}
public function getAlias(string $abstract): string {
if (isset($this->bind[$abstract])) {
$bind = $this->bind[$abstract];
if (is_string($bind)) {
return $this->getAlias($bind);
}
}
return $abstract;
}
public function instance(string $abstract, $instance) {
$abstract = $this->getAlias($abstract);
$this->instances[$abstract] = $instance;
return $this;
}
public function bound(string $abstract): bool {
return isset($this->bind[$abstract]) || isset($this->instances[$abstract]);
}
public function has($name): bool {
return $this->bound($name);
}
public function exists(string $abstract): bool {
$abstract = $this->getAlias($abstract);
return isset($this->instances[$abstract]);
}
public function make(string $abstract, array $vars = [], bool $newInstance = false) {
$abstract = $this->getAlias($abstract);
if (isset($this->instances[$abstract]) && !$newInstance) {
return $this->instances[$abstract];
}
if (isset($this->bind[$abstract]) && $this->bind[$abstract] instanceof Closure) {
$object = $this->invokeFunction($this->bind[$abstract], $vars);
} else {
$object = $this->invokeClass($abstract, $vars);
}
if (!$newInstance) {
$this->instances[$abstract] = $object;
}
return $object;
}
public function delete($name) {
$name = $this->getAlias($name);
if (isset($this->instances[$name])) {
unset($this->instances[$name]);
}
}
public function invokeFunction($function, array $vars = []) {
try {
$reflect = new ReflectionFunction($function);
} catch (ReflectionException $e) {
throw new FuncNotFoundException("function not exists: {$function}()", $function, $e);
}
$args = $this->bindParams($reflect, $vars);
return $function(...$args);
}
public function invokeMethod($method, array $vars = [], bool $accessible = false) {
if (is_array($method)) {
[$class, $method] = $method;
$class = is_object($class) ? $class : $this->invokeClass($class);
} else {
[$class, $method] = explode('::', $method);
}
try {
$reflect = new ReflectionMethod($class, $method);
} catch (ReflectionException $e) {
$class = is_object($class) ? get_class($class) : $class;
throw new FuncNotFoundException('method not exists: ' . $class . '::' . $method . '()', "{$class}::{$method}", $e);
}
$args = $this->bindParams($reflect, $vars);
if ($accessible) {
$reflect->setAccessible($accessible);
}
return $reflect->invokeArgs(is_object($class) ? $class : null, $args);
}
public function invokeReflectMethod($instance, $reflect, array $vars = []) {
$args = $this->bindParams($reflect, $vars);
return $reflect->invokeArgs($instance, $args);
}
public function invoke($callable, array $vars = [], bool $accessible = false) {
if ($callable instanceof Closure) {
return $this->invokeFunction($callable, $vars);
} elseif (is_string($callable) && false === strpos($callable, '::')) {
return $this->invokeFunction($callable, $vars);
} else {
return $this->invokeMethod($callable, $vars, $accessible);
}
}
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')) {
$method = $reflect->getMethod('__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;
}
protected function invokeAfter(string $class, $object): void {
if (isset($this->invokeCallback['*'])) {
foreach ($this->invokeCallback['*'] as $callback) {
$callback($object, $this);
}
}
if (isset($this->invokeCallback[$class])) {
foreach ($this->invokeCallback[$class] as $callback) {
$callback($object, $this);
}
}
}
protected function bindParams(ReflectionFunctionAbstract $reflect, array $vars = []): array {
if ($reflect->getNumberOfParameters() == 0) {
return [];
}
reset($vars);
$type = key($vars) === 0 ? 1 : 0;
$params = $reflect->getParameters();
$args = [];
foreach ($params as $param) {
$name = $param->getName();
$lowerName = Str::snake($name);
$reflectionType = $param->getType();
if ($reflectionType && $reflectionType->isBuiltin() === false) {
$args[] = $this->getObjectParam($reflectionType->getName(), $vars);
} elseif (1 == $type && !empty($vars)) {
$args[] = array_shift($vars);
} elseif (0 == $type && array_key_exists($name, $vars)) {
$args[] = $vars[$name];
} elseif (0 == $type && array_key_exists($lowerName, $vars)) {
$args[] = $vars[$lowerName];
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue();
} else {
throw new InvalidArgumentException('method param miss:' . $name);
}
}
return $args;
}
public static function factory(string $name, string $namespace = '', ...$args) {
$class = false !== strpos($name, '\\') ? $name : $namespace . ucwords($name);
return Container::getInstance()->invokeClass($class, $args);
}
protected function getObjectParam(string $className, array &$vars) {
$array = $vars;
$value = array_shift($array);
if ($value instanceof $className) {
$result = $value;
array_shift($vars);
} else {
$result = $this->make($className);
}
return $result;
}
public function __set($name, $value) {
$this->bind($name, $value);
}
public function __get($name) {
return $this->get($name);
}
public function __isset($name): bool {
return $this->exists($name);
}
public function __unset($name) {
$this->delete($name);
}
public function offsetExists($key) {
return $this->exists($key);
}
public function offsetGet($key) {
return $this->make($key);
}
public function offsetSet($key, $value) {
$this->bind($key, $value);
}
public function offsetUnset($key) {
$this->delete($key);
}
public function count() {
return count($this->instances);
}
public function getIterator() {
return new ArrayIterator($this->instances);
}
}
2.2 think\app.php 源码分析
<?php
namespace think;
use think\event\AppInit;
use think\helper\Str;
use think\initializer\BootService;
use think\initializer\Error;
use think\initializer\RegisterService;
class App extends Container {
const VERSION = '6.0.9';
protected $appDebug = false;
protected $envName = '';
protected $beginTime;
protected $beginMem;
protected $namespace = 'app';
protected $rootPath = '';
protected $thinkPath = '';
protected $appPath = '';
protected $runtimePath = '';
protected $routePath = '';
protected $configExt = '.php';
protected $initializers = [
Error::class,
RegisterService::class,
BootService::class,
];
protected $services = [];
protected $initialized = false;
protected $bind = [
'app' => App::class,
'cache' => Cache::class,
'config' => Config::class,
'console' => Console::class,
'cookie' => Cookie::class,
'db' => Db::class,
'env' => Env::class,
'event' => Event::class,
'http' => Http::class,
'lang' => Lang::class,
'log' => Log::class,
'middleware' => Middleware::class,
'request' => Request::class,
'response' => Response::class,
'route' => Route::class,
'session' => Session::class,
'validate' => Validate::class,
'view' => View::class,
'filesystem' => Filesystem::class,
'think\DbManager' => Db::class,
'think\LogManager' => Log::class,
'think\CacheManager' => Cache::class,
'Psr\Log\LoggerInterface' => Log::class,
];
public function __construct(string $rootPath = '') {
$this->thinkPath = 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('app', $this);
$this->instance('think\Container', $this);
}
public function register($service, bool $force = false) {
$registered = $this->getService($service);
if ($registered && !$force) {
return $registered;
}
if (is_string($service)) {
$service = new $service($this);
}
if (method_exists($service, 'register')) {
$service->register();
}
if (property_exists($service, 'bind')) {
$this->bind($service->bind);
}
$this->services[] = $service;
}
public function bootService($service) {
if (method_exists($service, 'boot')) {
return $this->invoke([$service, 'boot']);
}
}
public function getService($service) {
$name = is_string($service) ? $service : get_class($service);
return array_values(array_filter($this->services, function ($value) use ($name) {
return $value instanceof $name;
}, ARRAY_FILTER_USE_BOTH))[0] ?? null;
}
public function debug(bool $debug = true) {
$this->appDebug = $debug;
return $this;
}
public function isDebug(): bool {
return $this->appDebug;
}
public function setNamespace(string $namespace) {
$this->namespace = $namespace;
return $this;
}
public function getNamespace(): string {
return $this->namespace;
}
public function setEnvName(string $name) {
$this->envName = $name;
return $this;
}
public function version(): string {
return static::VERSION;
}
public function getRootPath(): string {
return $this->rootPath;
}
public function getBasePath(): string {
return $this->rootPath . 'app' . DIRECTORY_SEPARATOR;
}
public function getAppPath(): string {
return $this->appPath;
}
public function setAppPath(string $path) {
$this->appPath = $path;
}
public function getRuntimePath(): string {
return $this->runtimePath;
}
public function setRuntimePath(string $path): void {
$this->runtimePath = $path;
}
public function getThinkPath(): string {
return $this->thinkPath;
}
public function getConfigPath(): string {
return $this->rootPath . 'config' . DIRECTORY_SEPARATOR;
}
public function getConfigExt(): string {
return $this->configExt;
}
public function getBeginTime(): float {
return $this->beginTime;
}
public function getBeginMem(): int {
return $this->beginMem;
}
public function loadEnv(string $envName = ''): void {
$envFile = $envName ? $this->rootPath . '.env.' . $envName : $this->rootPath . '.env';
if (is_file($envFile)) {
$this->env->load($envFile);
}
}
public function initialize() {
$this->initialized = true;
$this->beginTime = microtime(true);
$this->beginMem = memory_get_usage();
$this->loadEnv($this->envName);
$this->configExt = $this->env->get('config_ext', '.php');
$this->debugModeInit();
$this->load();
$langSet = $this->lang->defaultLangSet();
$this->lang->load($this->thinkPath . 'lang' . DIRECTORY_SEPARATOR . $langSet . '.php');
$this->loadLangPack($langSet);
$this->event->trigger(AppInit::class);
date_default_timezone_set($this->config->get('app.default_timezone', 'Asia/Shanghai'));
foreach ($this->initializers as $initializer) {
$this->make($initializer)->init($this);
}
return $this;
}
public function initialized() {
return $this->initialized;
}
public function loadLangPack($langset) {
if (empty($langset)) {
return;
}
$files = glob($this->appPath . 'lang' . DIRECTORY_SEPARATOR . $langset . '.*');
$this->lang->load($files);
$list = $this->config->get('lang.extend_list', []);
if (isset($list[$langset])) {
$this->lang->load($list[$langset]);
}
}
public function boot(): void {
array_walk($this->services, function ($service) {
$this->bootService($service);
});
}
protected function load(): void {
$appPath = $this->getAppPath();
if (is_file($appPath . 'common.php')) {
include_once $appPath . 'common.php';
}
include_once $this->thinkPath . 'helper.php';
$configPath = $this->getConfigPath();
$files = [];
if (is_dir($configPath)) {
$files = glob($configPath . '*' . $this->configExt);
}
foreach ($files as $file) {
$this->config->load($file, pathinfo($file, PATHINFO_FILENAME));
}
if (is_file($appPath . 'event.php')) {
$this->loadEvent(include $appPath . 'event.php');
}
if (is_file($appPath . 'service.php')) {
$services = include $appPath . 'service.php';
foreach ($services as $service) {
$this->register($service);
}
}
}
protected function debugModeInit(): void {
if (!$this->appDebug) {
$this->appDebug = $this->env->get('app_debug') ? true : false;
ini_set('display_errors', 'Off');
}
if (!$this->runningInConsole()) {
if (ob_get_level() > 0) {
$output = ob_get_clean();
}
ob_start();
if (!empty($output)) {
echo $output;
}
}
}
public function loadEvent(array $event): void {
if (isset($event['bind'])) {
$this->event->bind($event['bind']);
}
if (isset($event['listen'])) {
$this->event->listenEvents($event['listen']);
}
if (isset($event['subscribe'])) {
$this->event->subscribe($event['subscribe']);
}
}
public function parseClass(string $layer, string $name): string {
$name = str_replace(['/', '.'], '\\', $name);
$array = explode('\\', $name);
$class = Str::studly(array_pop($array));
$path = $array ? implode('\\', $array) . '\\' : '';
return $this->namespace . '\\' . $layer . '\\' . $path . $class;
}
* @return bool
*/
public function runningInConsole(): bool {
return php_sapi_name() === 'cli' || php_sapi_name() === 'phpdbg';
}
protected function getDefaultRootPath(): string {
return dirname($this->thinkPath, 4) . DIRECTORY_SEPARATOR;
}
}
三、设全局环境变量
四、获取 http 服务
4.1 think\http.php源码分析
<?php
declare (strict_types=1);
namespace think;
use think\event\HttpEnd;
use think\event\HttpRun;
use think\event\RouteLoaded;
use think\exception\Handle;
use Throwable;
class Http {
protected $app;
protected $name;
protected $path;
protected $routePath;
protected $isBind = false;
public function __construct(App $app) {
$this->app = $app;
$this->routePath = $this->app->getRootPath() . 'route' . DIRECTORY_SEPARATOR;
}
public function name(string $name) {
$this->name = $name;
return $this;
}
public function getName(): string {
return $this->name ?: '';
}
public function path(string $path) {
if (substr($path, -1) != DIRECTORY_SEPARATOR) {
$path .= DIRECTORY_SEPARATOR;
}
$this->path = $path;
return $this;
}
public function getPath(): string {
return $this->path ?: '';
}
public function getRoutePath(): string {
return $this->routePath;
}
public function setRoutePath(string $path): void {
$this->routePath = $path;
}
public function setBind(bool $bind = true) {
$this->isBind = $bind;
return $this;
}
public function isBind(): bool {
return $this->isBind;
}
public function run(Request $request = null): Response {
$this->initialize();
$request = $request ?? $this->app->make('request', [], true);
$this->app->instance('request', $request);
try {
$response = $this->runWithRequest($request);
} catch (Throwable $e) {
$this->reportException($e);
$response = $this->renderException($request, $e);
}
return $response;
}
protected function initialize() {
if (!$this->app->initialized()) {
$this->app->initialize();
}
}
protected function runWithRequest(Request $request) {
$this->loadMiddleware();
$this->app->event->trigger(HttpRun::class);
return $this->app->middleware->pipeline()
->send($request)
->then(function ($request) {
return $this->dispatchToRoute($request);
});
}
protected function dispatchToRoute($request) {
$withRoute = $this->app->config->get('app.with_route', true) ? function () {
$this->loadRoutes();
} : null;
return $this->app->route->dispatch($request, $withRoute);
}
protected function loadMiddleware(): void {
if (is_file($this->app->getBasePath() . 'middleware.php')) {
$this->app->middleware->import(include $this->app->getBasePath() . 'middleware.php');
}
}
protected function loadRoutes(): void {
$routePath = $this->getRoutePath();
if (is_dir($routePath)) {
$files = glob($routePath . '*.php');
foreach ($files as $file) {
include $file;
}
}
$this->app->event->trigger(RouteLoaded::class);
}
protected function reportException(Throwable $e) {
$this->app->make(Handle::class)->report($e);
}
protected function renderException($request, Throwable $e) {
return $this->app->make(Handle::class)->render($request, $e);
}
public function end(Response $response): void {
$this->app->event->trigger(HttpEnd::class, $response);
$this->app->middleware->end($response);
$this->app->log->save();
}
}
http 执行流程
1, 执行http的run() 方法, run里执行三件事:http初始化,通过 $this->app->make(‘request’, [], true) 函数创建
r
e
q
u
e
s
t
对
象
,
将
request 对象,将
request对象,将request对象与app() 容器当中的request实例绑定
2,在try……catch 中执行应用程序 runWithRequest(),里面执行三件事:加载全局中间件,通过 $this->app->event->trigger 来监听 httpRun 类,将
t
h
i
s
?
>
a
p
p
?
>
m
i
d
d
l
e
w
a
r
e
?
>
p
i
p
e
l
i
n
e
(
)
?
>
s
e
n
d
(
this->app->middleware->pipeline()->send(
this?>app?>middleware?>pipeline()?>send(request)->then(function($requeszt){return
t
h
i
s
?
>
d
i
s
p
a
t
c
h
T
o
R
o
u
t
e
(
this->dispatchToRoute(
this?>dispatchToRoute(request)}) 结果集返回
3, 响应结果集,返回 $response;
在第2步的匿名方法中,dispatchToRoute() 会通过app->config->get() 方法,加载 app.with_route 路由开启配置,如果路由开启了,则去执行匿名方法,匿名方法内通过 $this->loadRoutes() 来加载路由,反之则不加载
4.2 think\request.php源码分析
<?php
namespace think;
use ArrayAccess;
use think\file\UploadedFile;
use think\route\Rule;
class Request implements ArrayAccess {
protected $pathinfoFetch = ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'];
protected $varPathinfo = 's';
protected $varMethod = '_method';
protected $varAjax = '_ajax';
protected $varPjax = '_pjax';
protected $rootDomain = '';
protected $httpsAgentName = '';
protected $proxyServerIp = [];
protected $proxyServerIpHeader = ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'];
protected $method;
protected $domain;
protected $host;
protected $subDomain;
protected $panDomain;
protected $url;
protected $baseUrl;
protected $baseFile;
protected $root;
protected $pathinfo;
protected $path;
protected $realIP;
protected $controller;
protected $action;
protected $param = [];
protected $get = [];
protected $post = [];
protected $request = [];
protected $rule;
protected $route = [];
protected $middleware = [];
protected $put;
protected $session;
protected $cookie = [];
protected $env;
protected $server = [];
protected $file = [];
protected $header = [];
protected $mimeType = [
'xml' => 'application/xml,text/xml,application/x-xml',
'json' => 'application/json,text/x-json,application/jsonrequest,text/json',
'js' => 'text/javascript,application/javascript,application/x-javascript',
'css' => 'text/css',
'rss' => 'application/rss+xml',
'yaml' => 'application/x-yaml,text/yaml',
'atom' => 'application/atom+xml',
'pdf' => 'application/pdf',
'text' => 'text/plain',
'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
'csv' => 'text/csv',
'html' => 'text/html,application/xhtml+xml,*/*',
];
protected $content;
protected $filter;
protected $input;
protected $secureKey;
protected $mergeParam = false;
public function __construct() {
$this->input = file_get_contents('php://input');
}
public static function __make(App $app) {
$request = new static();
if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
$header = $result;
} else {
$header = [];
$server = $_SERVER;
foreach ($server as $key => $val) {
if (0 === strpos($key, 'HTTP_')) {
$key = str_replace('_', '-', strtolower(substr($key, 5)));
$header[$key] = $val;
}
}
if (isset($server['CONTENT_TYPE'])) {
$header['content-type'] = $server['CONTENT_TYPE'];
}
if (isset($server['CONTENT_LENGTH'])) {
$header['content-length'] = $server['CONTENT_LENGTH'];
}
}
$request->header = array_change_key_case($header);
$request->server = $_SERVER;
$request->env = $app->env;
$inputData = $request->getInputData($request->input);
$request->get = $_GET;
$request->post = $_POST ?: $inputData;
$request->put = $inputData;
$request->request = $_REQUEST;
$request->cookie = $_COOKIE;
$request->file = $_FILES ?? [];
return $request;
}
public function setDomain(string $domain) {
$this->domain = $domain;
return $this;
}
public function domain(bool $port = false): string {
return $this->scheme() . '://' . $this->host($port);
}
public function rootDomain(): string {
$root = $this->rootDomain;
if (!$root) {
$item = explode('.', $this->host());
$count = count($item);
$root = $count > 1 ? $item[$count - 2] . '.' . $item[$count - 1] : $item[0];
}
return $root;
}
public function setSubDomain(string $domain) {
$this->subDomain = $domain;
return $this;
}
public function subDomain(): string {
if (is_null($this->subDomain)) {
$rootDomain = $this->rootDomain();
if ($rootDomain) {
$sub = stristr($this->host(), $rootDomain, true);
$this->subDomain = $sub ? rtrim($sub, '.') : '';
} else {
$this->subDomain = '';
}
}
return $this->subDomain;
}
public function setPanDomain(string $domain) {
$this->panDomain = $domain;
return $this;
}
public function panDomain(): string {
return $this->panDomain ?: '';
}
public function setUrl(string $url) {
$this->url = $url;
return $this;
}
public function url(bool $complete = false): string {
if ($this->url) {
$url = $this->url;
} elseif ($this->server('HTTP_X_REWRITE_URL')) {
$url = $this->server('HTTP_X_REWRITE_URL');
} elseif ($this->server('REQUEST_URI')) {
$url = $this->server('REQUEST_URI');
} elseif ($this->server('ORIG_PATH_INFO')) {
$url = $this->server('ORIG_PATH_INFO') . (!empty($this->server('QUERY_STRING')) ? '?' . $this->server('QUERY_STRING') : '');
} elseif (isset($_SERVER['argv'][1])) {
$url = $_SERVER['argv'][1];
} else {
$url = '';
}
return $complete ? $this->domain() . $url : $url;
}
public function setBaseUrl(string $url) {
$this->baseUrl = $url;
return $this;
}
public function baseUrl(bool $complete = false): string {
if (!$this->baseUrl) {
$str = $this->url();
$this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str;
}
return $complete ? $this->domain() . $this->baseUrl : $this->baseUrl;
}
public function baseFile(bool $complete = false): string {
if (!$this->baseFile) {
$url = '';
if (!$this->isCli()) {
$script_name = basename($this->server('SCRIPT_FILENAME'));
if (basename($this->server('SCRIPT_NAME')) === $script_name) {
$url = $this->server('SCRIPT_NAME');
} elseif (basename($this->server('PHP_SELF')) === $script_name) {
$url = $this->server('PHP_SELF');
} elseif (basename($this->server('ORIG_SCRIPT_NAME')) === $script_name) {
$url = $this->server('ORIG_SCRIPT_NAME');
} elseif (($pos = strpos($this->server('PHP_SELF'), '/' . $script_name)) !== false) {
$url = substr($this->server('SCRIPT_NAME'), 0, $pos) . '/' . $script_name;
} elseif ($this->server('DOCUMENT_ROOT') && strpos($this->server('SCRIPT_FILENAME'), $this->server('DOCUMENT_ROOT')) === 0) {
$url = str_replace('\\', '/', str_replace($this->server('DOCUMENT_ROOT'), '', $this->server('SCRIPT_FILENAME')));
}
}
$this->baseFile = $url;
}
return $complete ? $this->domain() . $this->baseFile : $this->baseFile;
}
public function setRoot(string $url) {
$this->root = $url;
return $this;
}
public function root(bool $complete = false): string {
if (!$this->root) {
$file = $this->baseFile();
if ($file && 0 !== strpos($this->url(), $file)) {
$file = str_replace('\\', '/', dirname($file));
}
$this->root = rtrim($file, '/');
}
return $complete ? $this->domain() . $this->root : $this->root;
}
public function rootUrl(): string {
$base = $this->root();
$root = strpos($base, '.') ? ltrim(dirname($base), DIRECTORY_SEPARATOR) : $base;
if ('' != $root) {
$root = '/' . ltrim($root, '/');
}
return $root;
}
public function setPathinfo(string $pathinfo) {
$this->pathinfo = $pathinfo;
return $this;
}
public function pathinfo(): string {
if (is_null($this->pathinfo)) {
if (isset($_GET[$this->varPathinfo])) {
$pathinfo = $_GET[$this->varPathinfo];
unset($_GET[$this->varPathinfo]);
unset($this->get[$this->varPathinfo]);
} elseif ($this->server('PATH_INFO')) {
$pathinfo = $this->server('PATH_INFO');
} elseif (false !== strpos(PHP_SAPI, 'cli')) {
$pathinfo = strpos($this->server('REQUEST_URI'), '?') ? strstr($this->server('REQUEST_URI'), '?', true) : $this->server('REQUEST_URI');
}
if (!isset($pathinfo)) {
foreach ($this->pathinfoFetch as $type) {
if ($this->server($type)) {
$pathinfo = (0 === strpos($this->server($type), $this->server('SCRIPT_NAME'))) ?
substr($this->server($type), strlen($this->server('SCRIPT_NAME'))) : $this->server($type);
break;
}
}
}
if (!empty($pathinfo)) {
unset($this->get[$pathinfo], $this->request[$pathinfo]);
}
$this->pathinfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
}
return $this->pathinfo;
}
public function ext(): string {
return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
}
public function time(bool $float = false) {
return $float ? $this->server('REQUEST_TIME_FLOAT') : $this->server('REQUEST_TIME');
}
public function type(): string {
$accept = $this->server('HTTP_ACCEPT');
if (empty($accept)) {
return '';
}
foreach ($this->mimeType as $key => $val) {
$array = explode(',', $val);
foreach ($array as $k => $v) {
if (stristr($accept, $v)) {
return $key;
}
}
}
return '';
}
public function mimeType($type, $val = ''): void {
if (is_array($type)) {
$this->mimeType = array_merge($this->mimeType, $type);
} else {
$this->mimeType[$type] = $val;
}
}
public function setMethod(string $method) {
$this->method = strtoupper($method);
return $this;
}
public function method(bool $origin = false): string {
if ($origin) {
return $this->server('REQUEST_METHOD') ?: 'GET';
} elseif (!$this->method) {
if (isset($this->post[$this->varMethod])) {
$method = strtolower($this->post[$this->varMethod]);
if (in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
$this->method = strtoupper($method);
$this->{$method} = $this->post;
} else {
$this->method = 'POST';
}
unset($this->post[$this->varMethod]);
} elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
$this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
} else {
$this->method = $this->server('REQUEST_METHOD') ?: 'GET';
}
}
return $this->method;
}
public function isGet(): bool {
return $this->method() == 'GET';
}
public function isPost(): bool {
return $this->method() == 'POST';
}
public function isPut(): bool {
return $this->method() == 'PUT';
}
public function isDelete(): bool {
return $this->method() == 'DELETE';
}
public function isHead(): bool {
return $this->method() == 'HEAD';
}
public function isPatch(): bool {
return $this->method() == 'PATCH';
}
public function isOptions(): bool {
return $this->method() == 'OPTIONS';
}
public function isCli(): bool {
return PHP_SAPI == 'cli';
}
public function isCgi(): bool {
return strpos(PHP_SAPI, 'cgi') === 0;
}
public function param($name = '', $default = null, $filter = '') {
if (empty($this->mergeParam)) {
$method = $this->method(true);
switch ($method) {
case 'POST':
$vars = $this->post(false);
break;
case 'PUT':
case 'DELETE':
case 'PATCH':
$vars = $this->put(false);
break;
default:
$vars = [];
}
$this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
$this->mergeParam = true;
}
if (is_array($name)) {
return $this->only($name, $this->param, $filter);
}
return $this->input($this->param, $name, $default, $filter);
}
public function all($name = '', $filter = '') {
$data = array_merge($this->param(), $this->file() ?: []);
if (is_array($name)) {
$data = $this->only($name, $data, $filter);
} elseif ($name) {
$data = $data[$name] ?? null;
}
return $data;
}
public function setRule(Rule $rule) {
$this->rule = $rule;
return $this;
}
public function rule() {
return $this->rule;
}
public function setRoute(array $route) {
$this->route = array_merge($this->route, $route);
$this->mergeParam = false;
return $this;
}
public function route($name = '', $default = null, $filter = '') {
if (is_array($name)) {
return $this->only($name, $this->route, $filter);
}
return $this->input($this->route, $name, $default, $filter);
}
public function get($name = '', $default = null, $filter = '') {
if (is_array($name)) {
return $this->only($name, $this->get, $filter);
}
return $this->input($this->get, $name, $default, $filter);
}
public function middleware($name, $default = null) {
return $this->middleware[$name] ?? $default;
}
public function post($name = '', $default = null, $filter = '') {
if (is_array($name)) {
return $this->only($name, $this->post, $filter);
}
return $this->input($this->post, $name, $default, $filter);
}
public function put($name = '', $default = null, $filter = '') {
if (is_array($name)) {
return $this->only($name, $this->put, $filter);
}
return $this->input($this->put, $name, $default, $filter);
}
protected function getInputData($content): array {
$contentType = $this->contentType();
if ('application/x-www-form-urlencoded' == $contentType) {
parse_str($content, $data);
return $data;
} elseif (false !== strpos($contentType, 'json')) {
return (array)json_decode($content, true);
}
return [];
}
public function delete($name = '', $default = null, $filter = '') {
return $this->put($name, $default, $filter);
}
public function patch($name = '', $default = null, $filter = '') {
return $this->put($name, $default, $filter);
}
public function request($name = '', $default = null, $filter = '') {
if (is_array($name)) {
return $this->only($name, $this->request, $filter);
}
return $this->input($this->request, $name, $default, $filter);
}
public function env(string $name = '', string $default = null) {
if (empty($name)) {
return $this->env->get();
} else {
$name = strtoupper($name);
}
return $this->env->get($name, $default);
}
public function session(string $name = '', $default = null) {
if ('' === $name) {
return $this->session->all();
}
return $this->session->get($name, $default);
}
public function cookie(string $name = '', $default = null, $filter = '') {
if (!empty($name)) {
$data = $this->getData($this->cookie, $name, $default);
} else {
$data = $this->cookie;
}
$filter = $this->getFilter($filter, $default);
if (is_array($data)) {
array_walk_recursive($data, [$this, 'filterValue'], $filter);
} else {
$this->filterValue($data, $name, $filter);
}
return $data;
}
public function server(string $name = '', string $default = '') {
if (empty($name)) {
return $this->server;
} else {
$name = strtoupper($name);
}
return $this->server[$name] ?? $default;
}
public function file(string $name = '') {
$files = $this->file;
if (!empty($files)) {
if (strpos($name, '.')) {
[$name, $sub] = explode('.', $name);
}
$array = $this->dealUploadFile($files, $name);
if ('' === $name) {
return $array;
} elseif (isset($sub) && isset($array[$name][$sub])) {
return $array[$name][$sub];
} elseif (isset($array[$name])) {
return $array[$name];
}
}
}
protected function dealUploadFile(array $files, string $name): array {
$array = [];
foreach ($files as $key => $file) {
if (is_array($file['name'])) {
$item = [];
$keys = array_keys($file);
$count = count($file['name']);
for ($i = 0; $i < $count; $i++) {
if ($file['error'][$i] > 0) {
if ($name == $key) {
$this->throwUploadFileError($file['error'][$i]);
} else {
continue;
}
}
$temp['key'] = $key;
foreach ($keys as $_key) {
$temp[$_key] = $file[$_key][$i];
}
$item[] = new UploadedFile($temp['tmp_name'], $temp['name'], $temp['type'], $temp['error']);
}
$array[$key] = $item;
} else {
if ($file instanceof File) {
$array[$key] = $file;
} else {
if ($file['error'] > 0) {
if ($key == $name) {
$this->throwUploadFileError($file['error']);
} else {
continue;
}
}
$array[$key] = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['error']);
}
}
}
return $array;
}
protected function throwUploadFileError($error) {
static $fileUploadErrors = [
1 => 'upload File size exceeds the maximum value',
2 => 'upload File size exceeds the maximum value',
3 => 'only the portion of file is uploaded',
4 => 'no file to uploaded',
6 => 'upload temp dir not found',
7 => 'file write error',
];
$msg = $fileUploadErrors[$error];
throw new Exception($msg, $error);
}
public function header(string $name = '', string $default = null) {
if ('' === $name) {
return $this->header;
}
$name = str_replace('_', '-', strtolower($name));
return $this->header[$name] ?? $default;
}
public function input(array $data = [], $name = '', $default = null, $filter = '') {
if (false === $name) {
return $data;
}
$name = (string)$name;
if ('' != $name) {
if (strpos($name, '/')) {
[$name, $type] = explode('/', $name);
}
$data = $this->getData($data, $name);
if (is_null($data)) {
return $default;
}
if (is_object($data)) {
return $data;
}
}
$data = $this->filterData($data, $filter, $name, $default);
if (isset($type) && $data !== $default) {
$this->typeCast($data, $type);
}
return $data;
}
protected function filterData($data, $filter, $name, $default) {
$filter = $this->getFilter($filter, $default);
if (is_array($data)) {
array_walk_recursive($data, [$this, 'filterValue'], $filter);
} else {
$this->filterValue($data, $name, $filter);
}
return $data;
}
public function isMobile(): bool {
if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
return true;
} elseif ($this->server('HTTP_ACCEPT') && strpos(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
return true;
} elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
return true;
} elseif ($this->server('HTTP_USER_AGENT') && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $this->server('HTTP_USER_AGENT'))) {
return true;
}
return false;
}
public function scheme(): string {
return $this->isSsl() ? 'https' : 'http';
}
public function query(): string {
return $this->server('QUERY_STRING', '');
}
public function setHost(string $host) {
$this->host = $host;
return $this;
}
public function host(bool $strict = false): string {
if ($this->host) {
$host = $this->host;
} else {
$host = strval($this->server('HTTP_X_FORWARDED_HOST') ?: $this->server('HTTP_HOST'));
}
return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
}
public function port(): int {
return (int)($this->server('HTTP_X_FORWARDED_PORT') ?: $this->server('SERVER_PORT', ''));
}
public function protocol(): string {
return $this->server('SERVER_PROTOCOL', '');
}
public function remotePort(): int {
return (int)$this->server('REMOTE_PORT', '');
}
public function contentType(): string {
$contentType = $this->header('Content-Type');
if ($contentType) {
if (strpos($contentType, ';')) {
[$type] = explode(';', $contentType);
} else {
$type = $contentType;
}
return trim($type);
}
return '';
}
public function secureKey(): string {
if (is_null($this->secureKey)) {
$this->secureKey = uniqid('', true);
}
return $this->secureKey;
}
public function setController(string $controller) {
$this->controller = $controller;
return $this;
}
public function setAction(string $action) {
$this->action = $action;
return $this;
}
public function controller(bool $convert = false): string {
$name = $this->controller ?: '';
return $convert ? strtolower($name) : $name;
}
public function action(bool $convert = false): string {
$name = $this->action ?: '';
return $convert ? strtolower($name) : $name;
}
public function getContent(): string {
if (is_null($this->content)) {
$this->content = $this->input;
}
return $this->content;
}
public function getInput(): string {
return $this->input;
}
public function buildToken(string $name = '__token__', $type = 'md5'): string {
$type = is_callable($type) ? $type : 'md5';
$token = call_user_func($type, $this->server('REQUEST_TIME_FLOAT'));
$this->session->set($name, $token);
return $token;
}
public function checkToken(string $token = '__token__', array $data = []): bool {
if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
return true;
}
if (!$this->session->has($token)) {
return false;
}
if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
$this->session->delete($token);
return true;
}
if (empty($data)) {
$data = $this->post();
}
if (isset($data[$token]) && $this->session->get($token) === $data[$token]) {
$this->session->delete($token);
return true;
}
$this->session->delete($token);
return false;
}
public function withMiddleware(array $middleware) {
$this->middleware = array_merge($this->middleware, $middleware);
return $this;
}
public function withGet(array $get) {
$this->get = $get;
return $this;
}
public function withPost(array $post) {
$this->post = $post;
return $this;
}
public function withCookie(array $cookie) {
$this->cookie = $cookie;
return $this;
}
public function withSession(Session $session) {
$this->session = $session;
return $this;
}
public function withServer(array $server) {
$this->server = array_change_key_case($server, CASE_UPPER);
return $this;
}
public function withHeader(array $header) {
$this->header = array_change_key_case($header);
return $this;
}
public function withEnv(Env $env) {
$this->env = $env;
return $this;
}
public function withInput(string $input) {
$this->input = $input;
if (!empty($input)) {
$inputData = $this->getInputData($input);
if (!empty($inputData)) {
$this->post = $inputData;
$this->put = $inputData;
}
}
return $this;
}
public function withFiles(array $files) {
$this->file = $files;
return $this;
}
public function withRoute(array $route) {
$this->route = $route;
return $this;
}
public function __set(string $name, $value) {
$this->middleware[$name] = $value;
}
public function __get(string $name) {
return $this->middleware($name);
}
public function __isset(string $name): bool {
return isset($this->middleware[$name]);
}
public function offsetExists($name): bool {
return $this->has($name);
}
public function offsetGet($name) {
return $this->param($name);
}
public function offsetSet($name, $value) {}
public function offsetUnset($name) {}
}
五、执行请求
think\response.php 源码分析
<?php
namespace think;
abstract class Response {
protected $data;
protected $contentType = 'text/html';
protected $charset = 'utf-8';
protected $code = 200;
protected $allowCache = true;
protected $options = [];
protected $header = [];
protected $content = null;
protected $cookie;
protected $session;
protected function init($data = '', int $code = 200) {
$this->data($data);
$this->code = $code;
$this->contentType($this->contentType, $this->charset);
}
public static function create($data = '', string $type = 'html', int $code = 200): Response {
$class = false !== strpos($type, '\\') ? $type : '\\think\\response\\' . ucfirst(strtolower($type));
return Container::getInstance()->invokeClass($class, [$data, $code]);
}
public function setSession(Session $session) {
$this->session = $session;
return $this;
}
public function send(): void {
$data = $this->getContent();
if (!headers_sent() && !empty($this->header)) {
http_response_code($this->code);
foreach ($this->header as $name => $val) {
header($name . (!is_null($val) ? ':' . $val : ''));
}
}
if ($this->cookie) {
$this->cookie->save();
}
$this->sendData($data);
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
}
protected function output($data) {
return $data;
}
protected function sendData(string $data): void {
echo $data;
}
public function options(array $options = []) {
$this->options = array_merge($this->options, $options);
return $this;
}
public function data($data) {
$this->data = $data;
return $this;
}
public function allowCache(bool $cache) {
$this->allowCache = $cache;
return $this;
}
public function isAllowCache() {
return $this->allowCache;
}
public function cookie(string $name, string $value, $option = null) {
$this->cookie->set($name, $value, $option);
return $this;
}
public function header(array $header = []) {
$this->header = array_merge($this->header, $header);
return $this;
}
public function content($content) {
if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable([
$content,
'__toString',
])
) {
throw new \InvalidArgumentException(sprintf('variable type error: %s', gettype($content)));
}
$this->content = (string)$content;
return $this;
}
public function code(int $code) {
$this->code = $code;
return $this;
}
public function lastModified(string $time) {
$this->header['Last-Modified'] = $time;
return $this;
}
public function expires(string $time) {
$this->header['Expires'] = $time;
return $this;
}
public function eTag(string $eTag) {
$this->header['ETag'] = $eTag;
return $this;
}
public function cacheControl(string $cache) {
$this->header['Cache-control'] = $cache;
return $this;
}
public function contentType(string $contentType, string $charset = 'utf-8') {
$this->header['Content-Type'] = $contentType . '; charset=' . $charset;
return $this;
}
public function getHeader(string $name = '') {
if (!empty($name)) {
return $this->header[$name] ?? null;
}
return $this->header;
}
public function getData() {
return $this->data;
}
public function getContent(): string {
if (null == $this->content) {
$content = $this->output($this->data);
if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable([
$content,
'__toString',
])
) {
throw new \InvalidArgumentException(sprintf('variable type error: %s', gettype($content)));
}
$this->content = (string)$content;
}
return $this->content;
}
public function getCode(): int {
return $this->code;
}
}
六、执行结束时的工作
$http->end($response);
|