Phalcon#系统架构#请求的生命周期

真实世界中当我们了解了一件工具的运行原理后,我们将能够更好的使用它,程序也是一样。现在框架大多是基于 MVC 的架构,Phalcon 也不例外。下面来看下 Phalcon 是如何来处理一个请求的。

首先看下 Phalcon 的入口程序 index.php,一个最基础的入口文件,主要做了哪些事情。

<?php
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;

// Register an autoloader
$loader = new Loader();
$loader->registerDirs( [ 
    "../app/controllers/", 
    "../app/models/", 
]);
$loader->register();

// Create a DI
$di = new FactoryDefault();

// Setup the view component
$di->set( "view", function () { 
    $view = new View(); 
    $view->setViewsDir("../app/views/");
    return $view;
});

// Setup a base URI so that all generated URIs include the "tutorial" folder
$di->set( "url", function () { 
    $url = new UrlProvider(); 
    $url->setBaseUri("/tutorial/"); 
    return $url; 
});

$application = new Application($di);

try { 
// Handle the request 
    $response = $application->handle(); 
    $response->send();
} catch (\Exception $e) { 
    echo "Exception: ", $e->getMessage();
}

程序中可以看到,入口文件主要干了以下事情:
1.创建自动加载器 $loader,注册自动加载目录;
2.创建服务容器 $di, 注册服务(其他一些服务使用默认的,如:路由 Router 服务。可以打印 $di查看已注册的服务);
3.创建程序对象 $application,运行程序 $application->handle()
4.发送响应的内容。
从以上几点可以看出,程序的主要处理逻辑还是在 Applicationhandle() 函数中,在到 handle() 函数中看下它做了什么事。

// ################################################
// 源码文件 cphalcon/phalcon/mvc/application.zep
// 这里截取 handle() 函数出来看下, 
// ################################################

 /**
     * Handles a MVC request
     */
    public function handle(string uri = null) -> <ResponseInterface> | boolean
    {
        var dependencyInjector, eventsManager, router, dispatcher, response, view,
            module, moduleObject, moduleName, className, path,
            implicitView, returnedResponse, controller, possibleResponse,
            renderStatus, matchedRoute, match;

        let dependencyInjector = this->_dependencyInjector;
        if typeof dependencyInjector != "object" {
            throw new Exception("A dependency injection object is required to access internal services");
        }

        let eventsManager = <ManagerInterface> this->_eventsManager;

        /**
         * Call boot event, this allow the developer to perform initialization actions
         */
        if typeof eventsManager == "object" {
            if eventsManager->fire("application:boot", this) === false {
                return false;
            }
        }

        let router = <RouterInterface> dependencyInjector->getShared("router");

        /**
         * Handle the URI pattern (if any)
         */
        router->handle(uri);

        /**
         * If a 'match' callback was defined in the matched route
         * The whole dispatcher+view behavior can be overriden by the developer
         */
        let matchedRoute = router->getMatchedRoute();
        if typeof matchedRoute == "object" {
            let match = matchedRoute->getMatch();
            if match !== null {

                if match instanceof \Closure {
                    let match = \Closure::bind(match, dependencyInjector);
                }

                /**
                 * Directly call the match callback
                 */
                let possibleResponse = call_user_func_array(match, router->getParams());

                /**
                 * If the returned value is a string return it as body
                 */
                if typeof possibleResponse == "string" {
                    let response = <ResponseInterface> dependencyInjector->getShared("response");
                    response->setContent(possibleResponse);
                    return response;
                }

                /**
                 * If the returned string is a ResponseInterface use it as response
                 */
                if typeof possibleResponse == "object" {
                    if possibleResponse instanceof ResponseInterface {
                        possibleResponse->sendHeaders();
                        possibleResponse->sendCookies();
                        return possibleResponse;
                    }
                }
            }
        }

        /**
         * If the router doesn't return a valid module we use the default module
         */
        let moduleName = router->getModuleName();
        if !moduleName {
            let moduleName = this->_defaultModule;
        }

        let moduleObject = null;

        /**
         * Process the module definition
         */
        if moduleName {

            if typeof eventsManager == "object" {
                if eventsManager->fire("application:beforeStartModule", this, moduleName) === false {
                    return false;
                }
            }

            /**
             * Gets the module definition
             */
            let module = this->getModule(moduleName);

            /**
             * A module definition must ne an array or an object
             */
            if typeof module != "array" && typeof module != "object" {
                throw new Exception("Invalid module definition");
            }

            /**
             * An array module definition contains a path to a module definition class
             */
            if typeof module == "array" {

                /**
                 * Class name used to load the module definition
                 */
                if !fetch className, module["className"] {
                    let className = "Module";
                }

                /**
                 * If developer specify a path try to include the file
                 */
                if fetch path, module["path"] {
                    if !class_exists(className, false) {
                        if !file_exists(path) {
                            throw new Exception("Module definition path '" . path . "' doesn't exist");
                        }

                        require path;
                    }
                }

                let moduleObject = <ModuleDefinitionInterface> dependencyInjector->get(className);

                /**
                 * 'registerAutoloaders' and 'registerServices' are automatically called
                 */
                moduleObject->registerAutoloaders(dependencyInjector);
                moduleObject->registerServices(dependencyInjector);

            } else {

                /**
                 * A module definition object, can be a Closure instance
                 */
                if !(module instanceof \Closure) {
                    throw new Exception("Invalid module definition");
                }

                let moduleObject = call_user_func_array(module, [dependencyInjector]);
            }

            /**
             * Calling afterStartModule event
             */
            if typeof eventsManager == "object" {
                eventsManager->fire("application:afterStartModule", this, moduleObject);
            }
        }

        /**
         * Check whether use implicit views or not
         */
        let implicitView = this->_implicitView;

        if implicitView === true {
            let view = <ViewInterface> dependencyInjector->getShared("view");
        }

        /**
         * We get the parameters from the router and assign them to the dispatcher
         * Assign the values passed from the router
         */
        let dispatcher = <DispatcherInterface> dependencyInjector->getShared("dispatcher");
        dispatcher->setModuleName(router->getModuleName());
        dispatcher->setNamespaceName(router->getNamespaceName());
        dispatcher->setControllerName(router->getControllerName());
        dispatcher->setActionName(router->getActionName());
        dispatcher->setParams(router->getParams());

        /**
         * Start the view component (start output buffering)
         */
        if implicitView === true {
            view->start();
        }

        /**
         * Calling beforeHandleRequest
         */
        if typeof eventsManager == "object" {
            if eventsManager->fire("application:beforeHandleRequest", this, dispatcher) === false {
                return false;
            }
        }

        /**
         * The dispatcher must return an object
         */
        let controller = dispatcher->dispatch();

        /**
         * Get the latest value returned by an action
         */
        let possibleResponse = dispatcher->getReturnedValue();

        /**
         * Returning false from an action cancels the view
         */
        if typeof possibleResponse == "boolean" && possibleResponse === false {
            let response = <ResponseInterface> dependencyInjector->getShared("response");
        } else {

            /**
             * Returning a string makes use it as the body of the response
             */
            if typeof possibleResponse == "string" {
                let response = <ResponseInterface> dependencyInjector->getShared("response");
                response->setContent(possibleResponse);
            } else {

                /**
                 * Check if the returned object is already a response
                 */
                let returnedResponse = ((typeof possibleResponse == "object") && (possibleResponse instanceof ResponseInterface));

                /**
                 * Calling afterHandleRequest
                 */
                if typeof eventsManager == "object" {
                    eventsManager->fire("application:afterHandleRequest", this, controller);
                }

                /**
                 * If the dispatcher returns an object we try to render the view in auto-rendering mode
                 */
                if returnedResponse === false && implicitView === true {
                    if typeof controller == "object" {

                        let renderStatus = true;

                        /**
                         * This allows to make a custom view render
                         */
                        if typeof eventsManager == "object" {
                            let renderStatus = eventsManager->fire("application:viewRender", this, view);
                        }

                        /**
                         * Check if the view process has been treated by the developer
                         */
                        if renderStatus !== false {

                            /**
                             * Automatic render based on the latest controller executed
                             */
                            view->render(
                                dispatcher->getControllerName(),
                                dispatcher->getActionName(),
                                dispatcher->getParams()
                            );
                        }
                    }
                }

                /**
                 * Finish the view component (stop output buffering)
                 */
                if implicitView === true {
                    view->finish();
                }

                if returnedResponse === true {

                    /**
                     * We don't need to create a response because there is one already created
                     */
                    let response = possibleResponse;
                } else {

                    let response = <ResponseInterface> dependencyInjector->getShared("response");
                    if implicitView === true {

                        /**
                         * The content returned by the view is passed to the response service
                         */
                        response->setContent(view->getContent());
                    }
                }
            }
        }

        /**
         * Calling beforeSendResponse
         */
        if typeof eventsManager == "object" {
            eventsManager->fire("application:beforeSendResponse", this, response);
        }

        /**
         * Headers and Cookies are automatically sent
         */
        response->sendHeaders();
        response->sendCookies();

        /**
         * Return the response
         */
        return response;
    }

函数handle()里主要干了这些事:
1.匹配路由;
2.调用派遣器,分发匹配的路由;
3.渲染视图;
4.返回响应对象 response
还有一些事件处理,具体查看源码了解。所以可以看出 Phalcon 请求的生命周期大致如下图所示:

Phalcon 请求的生命周期

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,142评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,298评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,068评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,081评论 1 291
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,099评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,071评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,990评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,832评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,274评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,488评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,649评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,378评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,979评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,625评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,796评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,643评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,545评论 2 352

推荐阅读更多精彩内容