Yii Framework Analysis (IV.) detailed analysis of the run function of--webapplication

Source: Internet
Author: User

The last sentence of the entry script for YII application started WebApplication

Yii::createwebapplication ($config)->run ();

CApplication:

Public Function Run () {    $this->onbeginrequest (New CEvent ($this));    $this->processrequest ();    $this->onendrequest (New CEvent ($this));}

ProcessRequest () begins processing the request, implemented by Cwebapplication:

Public Function ProcessRequest () {    if (Is_array ($this->catchallrequest) && isset ($this, Catchallrequest[0])    {        $route = $this->catchallrequest[0];        foreach (Array_splice ($this->catchallrequest,1) as $name = + $value)            $_get[$name]= $value;    }    else        $route = $this->geturlmanager ()->parseurl ($this->getrequest ());    $this->runcontroller ($route);}

The Urlmanager application component's parseURL () creates $route (a string in the form of Controllerid/actionid), and Runcontroller () creates a controller object to begin processing HTTP requests.

There are several possible scenarios for $route values:
-Empty: Replace with defaultcontroller value;
-"Moduleid/controllerid/actionid": Under Module
-"Controllerid/actionid": the most common form
-Controller in "Folder1/folder2/controllerid/actionid" Multilevel Directory

Runcontroller First Call Createcontroller () to create the Controller object

The Public Function Createcontroller ($route, $owner =null) {//$owner is empty is set to $this, which is the $_app object if ($owner ===null) $owner    = $this; $route null set to Defaultcontroller, configure if in $config (($route =trim ($route, '/')) = = = ") $route = $owner->defaultcontrolle    R    $caseSensitive = $this->geturlmanager ()->casesensitive;    $route. = '/';        Remove each $route by pressing the first segment of the '/' Division to process while (($pos =strpos ($route, '/'))!==false) {//$id is stored $route first '/' before        $id =substr ($route, 0, $pos);        if (!preg_match ('/^\w+$/', $id)) return null;        if (! $caseSensitive) $id =strtolower ($id);        $route store '/' after part $route = (string) substr ($route, $pos + 1); if (!isset ($basePath))//complete $route First paragraph {//if $id is mapped in controllermap[]//directly based on $ID to create controller Like if (Isset ($owner->controllermap[$id])) {return Array (YII::CR Eatecomponent ($owner->controllermap[$id], $id, $owner = = = $this? null: $owner), $this->parseactionparams ($route),); }//$id is a system-defined module that obtains the module object as the $owner parameter according to $id createcontroller if ($module = $owner->getmodule (            $id)!==null) return $this->createcontroller ($route, $module);            The directory where the controller resides $basePath = $owner->getcontrollerpath ();        $controllerID = ";        } else $controllerID. = '/'; $className =ucfirst ($id). '        Controller '; $classFile = $basePath. Directory_separator. $className.        PHP ';             Controller class file exists, then require and create Controller object & return if (Is_file ($classFile)) {if (!class_exists ($className, False))            Require ($classFile); if (Class_exists ($className, False) && is_subclass_of ($className, ' Ccontroller ')) {$id [0]=                Strtolower ($id [0]);      Return Array (new $className ($controllerID. $id, $owner = = = $this? Null: $owner),              $this->parseactionparams ($route),);        } return null;        }//The Controller class file could not be found, it could be a multilevel directory, continue to search for subdirectories $controllerID. = $id;    $basePath. =directory_separator. $id; }}

Createcontroller () returns a created controller object and ActionId, Runcontroller () calls the Controller's init () method and runs ($actionID) to run the controller:

Public Function Runcontroller ($route) {    if ($ca = $this->createcontroller ($route))!==null)    {        list ($ Controller, $actionID) = $ca;        $oldController = $this->_controller;        $this->_controller= $controller;        $controller->init ();        $controller->run ($actionID);        $this->_controller= $oldController;    }    else        throw new Chttpexception (404, Yii::t (' Yii ', ' unable to resolve the request ' {route} '. ', Array (' {route} ' = $r oute=== "? $this->defaultcontroller: $route)));    }

$controller->init () No action, run ():

Public function Run ($actionID) {    if ($action = $this->createaction ($actionID))!==null)    {       if ($parent = $this->getmodule ()) ===null)           $parent =yii::app ();       if ($parent->beforecontrolleraction ($this, $action))       {           $this->runactionwithfilters ($action, $this- >filters ());           $parent->aftercontrolleraction ($this, $action);       }    }    else        $this->missingaction ($actionID);}

The action object was first created $controller->run ($actionID):

Public Function CreateAction ($actionID) {    //null is set to DefaultAction    if ($actionID = = = ")        $actionID = $this DefaultAction;    There is ' action ' in the controller. $actionID method, create the Cinlineaction object    if (method_exists ($this, ' action '. $actionID) && STRCASECMP ($actionID, ' s '))//We have the Actions method        return new Cinlineaction ($this, $actionID);    Otherwise, the action object is created according to the actions map        $this->createactionfrommap ($this->actions (), $actionID, $ ActionId);}

You can see here that the controller does not call the action method directly, but instead requires an action object to run the controller action, which unifies the Controller method and the action object of the actions map to handle the action. That is, both forms of action processing are unified for the run () Call of the IAction interface.

The IAction interface requires the implementation of run (), GetId (), Getcontroller () three methods, and Yii provides a caction class that requires the constructor to provide the controller and ID and implements GETID () and Getcontroller () Handle, the action class inherits from the CAction.

Cinlineaction under Web/action, run () is a very simple process that invokes the Controller's action method:

Class Cinlineaction extends caction{public    function run ()    {        $method = ' action '. $this->getid ();        $this->getcontroller () $method ();    }}

Back to $controller->run ($actionID)

Public function Run ($actionID) {    if ($action = $this->createaction ($actionID))!==null)    {        if ($parent = $this->getmodule ()) ===null)            $parent =yii::app ();        if ($parent->beforecontrolleraction ($this, $action))        {            $this->runactionwithfilters ($action, $ This->filters ());            $parent->aftercontrolleraction ($this, $action);        }    }    else        $this->missingaction ($actionID);}

Yii::app ()->beforecontrolleraction () is actually fixed return true, so the action object is actually through the controller's Runactionwithfilters () run

Public Function Runactionwithfilters ($action, $filters) {    //Controller not set filter    if (empty ($filters))        $this Runaction ($action);    else    {        //Create filter chain object and run        $priorAction = $this->_action;        $this->_action= $action;        Cfilterchain::create ($this, $action, $filters)->run ();        $this->_action= $priorAction;    }}

Without a filter, runaction () is the run () method that ultimately calls the action object you created earlier:

Public Function Runaction ($action) {    $priorAction = $this->_action;    $this->_action= $action;    if ($this->beforeaction ($action))    {        $action->run ();        $this->afteraction ($action);    }    $this->_action= $priorAction;}

Each filter implements the IFilter interface, and the filter Implementation's Prefilter () method is called before $action->run () and returns true if the action can be executed, otherwise false

if ($filter 1->prefilter ())
if ($filter 2->prefilter ())
if ($filtern->prefilter ())
$action->run ()
$filtern->postfilter ()
$filter 2->postfilter ()
$filter 1->postfilter ()

The most common action in action is the render view file: RenderPartial () and render (). Render () will put the result in the layout file after processing the view file.

Public Function renderpartial ($view, $data =null, $return =false, $processOutput =false) {    if ($viewFile = $this Getviewfile ($view))!==false)    {        $output = $this->renderfile ($viewFile, $data, true);        if ($processOutput)            $output = $this->processoutput ($output);        if ($return)            return $output;        else            echo $output;    }    else        throw new CException (' yii::t ', ' {controller} cannot find the requested view ' {view} '. ',            Array (' { Controller} ' =>get_class ($this), ' {view} ' = $view)));

Getviewfile ($view) Get the full path to $view:
$view begins with '/' and takes the system views directory as the starting directory + $view +.php
$view an alias, find the True path to the alias
Other Modele view directories as the starting directory + $view +.php

If you do not configure a third party in $config, the Renderer,renderfile () actually invokes the renderinternal () provided by YII itself to render the view file:

Public Function RenderFile ($viewFile, $data =null, $return =false) {    $widgetCount =count ($this->_widgetstack);    If you have configured additional Viewrenderer    if (($renderer =yii::app ()->getviewrenderer ())!==null)        $content = $renderer RenderFile ($this, $viewFile, $data, $return);    else        //Yii's own render        $content = $this->renderinternal ($viewFile, $data, $return);    if (count ($this->_widgetstack) = = = $widgetCount)        return $content;    else    {        $widget =end ($this->_widgetstack);        throw new CException (Yii::t (' Yii ', ' {controller} contains improperly nested widget tags in its view ' {view} '. A {widget} widget does not has an endwidget () call. ', Array (' {controller} ' =>get_class ($this), ' {view} ' = = $viewFile , ' {widget} ' =>get_class ($widget)));}    }

The renderer of Yii uses PHP itself as a templating system:

The Public Function renderinternal ($_viewfile_,$_data_=null,$_return_=false) {    ///extract function will $_data_ Imports a variable from an array into the current symbol table    if (Is_array ($_data_))        extract ($_data_,extr_prefix_same, ' data ');    else        $data =$_data_;    if ($_return_)    {        ob_start ();        Ob_implicit_flush (false);        Require ($_viewfile_);        return Ob_get_clean ();    }    else        require ($_viewfile_);}

Render () is actually renderpartial the view file first, then RenderFile Layoutfile, and the result of the view file is passed in as a $content variable.

Public function render ($view, $data =null, $return =false) {    $output = $this->renderpartial ($view, $data, true);    if ($layoutFile = $this->getlayoutfile ($this->layout))!==false)        $output = $this->renderfile ($ Layoutfile,array (' content ' = $output), true);    $output = $this->processoutput ($output);    if ($return)        return $output;    else        echo $output;}

Processoutput the results of the render, such as the head with CSS or JS script.

Public Function Processoutput ($output) {    Yii::app ()->getclientscript ()->render ($output);    If using page caching, we should delay dynamic output replacement    if ($this->_dynamicoutput!==null && $th Is->iscachingstackempty ())        $output = $this->processdynamicoutput ($output);    if ($this->_pagestates===null)        $this->_pagestates= $this->loadpagestates ();    if (!empty ($this->_pagestates))        $this->savepagestates ($this->_pagestates, $output);    return $output;}

Yii Framework Analysis (IV.) detailed analysis of the run function of--webapplication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.