首先我们来看入口文件
1.加载配置文件。
2.执行run()方法。
2.1 run()方法里面有 handleRequest()处理请求、send()返回结果。
2.2 handleRequest()里面做了两件事 1解析出路由和请求参数;2执行路由方法。
以上是初略的分析。欢迎评论指正。
(new yii\web\Application($config))->run();
# new yii\web\Application($config))是加载配置参数
# 主要来看 run() 方法
public function run()
{
try {
//触发请求前事件 (开发人员根据需求自己定义)
$this->state = self::STATE_BEFORE_REQUEST;
$this->trigger(self::EVENT_BEFORE_REQUEST);
//处理请求
$this->state = self::STATE_HANDLING_REQUEST;
$response = $this->handleRequest($this->getRequest());
//触发请求后事件 (开发人员根据需求自己定义)
$this->state = self::STATE_AFTER_REQUEST;
$this->trigger(self::EVENT_AFTER_REQUEST);
//将结果返回给请求端
$this->state = self::STATE_SENDING_RESPONSE;
$response->send();
$this->state = self::STATE_END;
return $response->exitStatus;
} catch (ExitException $e) {
$this->end($e->statusCode, isset($response) ? $response : null);
return $e->statusCode;
}
}
public function handleRequest($request)
{
if (empty($this->catchAll)) {
try {
//resolve获取请求路由和请求参数
list($route, $params) = $request->resolve();
} catch (UrlNormalizerRedirectException $e) {
$url = $e->url;
if (is_array($url)) {
if (isset($url[0])) {
// ensure the route is absolute
$url[0] = '/' . ltrim($url[0], '/');
}
$url += $request->getQueryParams();
}
return $this->getResponse()->redirect(Url::to($url, $e->scheme), $e->statusCode);
}
} else {
$route = $this->catchAll[0];
$params = $this->catchAll;
unset($params[0]);
}
try {
Yii::debug("Route requested: '$route'", __METHOD__);
$this->requestedRoute = $route;
//执行路由的控制器下面的方法
$result = $this->runAction($route, $params);
//返回结果
if ($result instanceof Response) {
return $result;
}
$response = $this->getResponse();
if ($result !== null) {
$response->data = $result;
}
return $response;
} catch (InvalidRouteException $e) {
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'), $e->getCode(), $e);
}
}
public function runAction($route, $params = [])
{
//获取控制器名和方法名
$parts = $this->createController($route);
if (is_array($parts)) {
/* @var $controller Controller */
list($controller, $actionID) = $parts;
$oldController = Yii::$app->controller;
Yii::$app->controller = $controller;
//这里是执行方法
$result = $controller->runAction($actionID, $params);
if ($oldController !== null) {
Yii::$app->controller = $oldController;
}
//返回结果
return $result;
}