Phalcon#系統(tǒng)架構(gòu)#請(qǐng)求的生命周期

真實(shí)世界中當(dāng)我們了解了一件工具的運(yùn)行原理后,我們將能夠更好的使用它涡上,程序也是一樣≈憾希現(xiàn)在框架大多是基于 MVC 的架構(gòu),Phalcon 也不例外吩愧。下面來(lái)看下 Phalcon 是如何來(lái)處理一個(gè)請(qǐng)求的芋酌。

首先看下 Phalcon 的入口程序 index.php,一個(gè)最基礎(chǔ)的入口文件雁佳,主要做了哪些事情脐帝。

<?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.創(chuàng)建自動(dòng)加載器 $loader,注冊(cè)自動(dòng)加載目錄堵腹;
2.創(chuàng)建服務(wù)容器 $di炸站, 注冊(cè)服務(wù)(其他一些服務(wù)使用默認(rèn)的,如:路由 Router 服務(wù)疚顷『狄祝可以打印 $di查看已注冊(cè)的服務(wù));
3.創(chuàng)建程序?qū)ο?$application荡含,運(yùn)行程序 $application->handle()咒唆;
4.發(fā)送響應(yīng)的內(nèi)容。
從以上幾點(diǎn)可以看出释液,程序的主要處理邏輯還是在 Applicationhandle() 函數(shù)中全释,在到 handle() 函數(shù)中看下它做了什么事。

// ################################################
// 源碼文件 cphalcon/phalcon/mvc/application.zep
// 這里截取 handle() 函數(shù)出來(lái)看下误债, 
// ################################################

 /**
     * 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;
    }

函數(shù)handle()里主要干了這些事:
1.匹配路由浸船;
2.調(diào)用派遣器,分發(fā)匹配的路由寝蹈;
3.渲染視圖李命;
4.返回響應(yīng)對(duì)象 response
還有一些事件處理箫老,具體查看源碼了解封字。所以可以看出 Phalcon 請(qǐng)求的生命周期大致如下圖所示:

Phalcon 請(qǐng)求的生命周期

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市耍鬓,隨后出現(xiàn)的幾起案子阔籽,更是在濱河造成了極大的恐慌,老刑警劉巖牲蜀,帶你破解...
    沈念sama閱讀 212,542評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件笆制,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡涣达,警方通過(guò)查閱死者的電腦和手機(jī)在辆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,596評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)度苔,“玉大人匆篓,你說(shuō)我怎么就攤上這事】芤ぃ” “怎么了奕删?”我有些...
    開(kāi)封第一講書(shū)人閱讀 158,021評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)疗认。 經(jīng)常有香客問(wèn)我完残,道長(zhǎng)伏钠,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,682評(píng)論 1 284
  • 正文 為了忘掉前任谨设,我火速辦了婚禮熟掂,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘扎拣。我一直安慰自己赴肚,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,792評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布二蓝。 她就那樣靜靜地躺著誉券,像睡著了一般。 火紅的嫁衣襯著肌膚如雪刊愚。 梳的紋絲不亂的頭發(fā)上踊跟,一...
    開(kāi)封第一講書(shū)人閱讀 49,985評(píng)論 1 291
  • 那天,我揣著相機(jī)與錄音鸥诽,去河邊找鬼商玫。 笑死,一個(gè)胖子當(dāng)著我的面吹牛牡借,可吹牛的內(nèi)容都是我干的拳昌。 我是一名探鬼主播,決...
    沈念sama閱讀 39,107評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼钠龙,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼炬藤!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起碴里,我...
    開(kāi)封第一講書(shū)人閱讀 37,845評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤沈矿,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后并闲,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,299評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡谷羞,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,612評(píng)論 2 327
  • 正文 我和宋清朗相戀三年帝火,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片湃缎。...
    茶點(diǎn)故事閱讀 38,747評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡犀填,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出嗓违,到底是詐尸還是另有隱情九巡,我是刑警寧澤,帶...
    沈念sama閱讀 34,441評(píng)論 4 333
  • 正文 年R本政府宣布蹂季,位于F島的核電站冕广,受9級(jí)特大地震影響疏日,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜撒汉,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,072評(píng)論 3 317
  • 文/蒙蒙 一沟优、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧睬辐,春花似錦挠阁、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,828評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至丰刊,卻和暖如春隘谣,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背藻三。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,069評(píng)論 1 267
  • 我被黑心中介騙來(lái)泰國(guó)打工洪橘, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人棵帽。 一個(gè)月前我還...
    沈念sama閱讀 46,545評(píng)論 2 362
  • 正文 我出身青樓熄求,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親逗概。 傳聞我的和親對(duì)象是個(gè)殘疾皇子弟晚,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,658評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容