YII Source Code Analysis (2), yii Source Code Analysis _ PHP Tutorial

Source: Internet
Author: User
YII Source Code Analysis (2): yii source code analysis. YII Source Code Analysis (II): yii source code analysis the previous article briefly analyzed the yii process, from creating an application to outputting results on the screen. This time I came to a slightly more complex YII Source Code Analysis (2), yii source code analysis

The previous article briefly analyzed the yii process, from creating an application to outputting results on the screen. This time, I came up with a slightly more complex one, focusing on the output. it is no longer a simple line of "hello world", but it needs to be processed by the view layer.

It is still the demos Directory. this time we chose hangman, a simple guessing game. The old rule should be viewed from the entrance.

Index. php:

 run();

Compared with the helloworld application, main. php is added more this time. open main and check the source code:

 'Hangman Game',    'defaultController'=>'game',    'components'=>array(        'urlManager'=>array(            'urlFormat'=>'path',            'rules'=>array(                'game/guess/
 
  '=>'game/guess',            ),        ),    ),);
 

Configuration files are also frequently used in actual projects in the future, so I think it is necessary to understand the yii configuration file-main. php

'Name' => 'usually the website title', that is, the title displayed on the webpage when index. php is opened.

'Defaultcontroller' => 'here is the default controller', that is, the controller used by the system when no controller is specified after index. php. if we do not specify this controller, the default controller is site.

'Components' => 'here is the component parameter, which is configured with a multi-dimensional array. 'Specific parameters can be viewed in the yii manual.

Yii: createWebApplication ($ config)-> run (); the last time we analyzed it in detail, let's simply go over it:

CWebApplication. php-> CApplication. php-> _ construct ($ config ):

$this->preinit();        $this->initSystemHandlers();        $this->registerCoreComponents();        $this->configure($config);        $this->attachBehaviors($this->behaviors);        $this->preloadComponents();        $this->init();

We didn't configure the process last time, so $ this-> configure ($ config) didn't do anything, but this time there were configuration parameters, so let's go in and see what yii has done:

CApplication itself does not implement the configure method, which is inherited from CModule. php:

    public function configure($config)    {        if(is_array($config))        {            foreach($config as $key=>$value)                $this->$key=$value;        }    }

The code is very simple, that is, the configuration parameter key is used as the class attribute name, and the value is extended as the class attribute value. After completing this process, run the run method on CApplication.

    public function run()    {        if($this->hasEventHandler('onBeginRequest'))            $this->onBeginRequest(new CEvent($this));        register_shutdown_function(array($this,'end'),0,false);        $this->processRequest();        if($this->hasEventHandler('onEndRequest'))            $this->onEndRequest(new CEvent($this));    }

As we mentioned earlier, you only need to pay attention to $ this-> processRequest. The execution result is $ this-> runController ('');

    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}'=>$route===''?$this->defaultController:$route)));    }

Because the url is index. php, there is no parameter in the end, so it is the default controller, that is, we are in the main. php game. therefore, $ controller is equal to controllers/gameController. php, we can know through the source code analysis of the previous time, in the gameController. when php does not have the init method, the default method defined in the parent class is used (actually an empty method ),

$ Controller-> run ($ actionID); = gameController-> run (''); the run method is not implemented on gameController, so you can find run in the parent class.

From the class GameController extends CController, we can see that the parent class is CController and find the corresponding run method:

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 analysis has been done before. If no timer is specified, the default parameters are used. At this time, $ actionID is blank, and actionID is the default action defined in gameController: public $ defaultAction = 'play ';

RunActionWithFilters ---> runAction --> $ action-> runWithParams

$ Action here needs to be found from CAction-> CInlineAction

public function runWithParams($params)    {        $methodName='action'.$this->getId();        $controller=$this->getController();        $method=new ReflectionMethod($controller, $methodName);        if($method->getNumberOfParameters()>0)            return $this->runWithParamsInternal($controller, $method, $params);        else            return $controller->$methodName();    }

The process is similar to that of hello world. According to the previous analysis, we can see that we have executed

$ Controller-> $ methodName (); that is, GameController-> actionPlay ()

At this point, the focus of this section really begins:
    public function actionPlay()    {        static $levels=array(            '10'=>'Easy game; you are allowed 10 misses.',            '5'=>'Medium game; you are allowed 5 misses.',            '3'=>'Hard game; you are allowed 3 misses.',        );        // if a difficulty level is correctly chosen        if(isset($_POST['level']) && isset($levels[$_POST['level']]))        {            $this->word=$this->generateWord();            $this->guessWord=str_repeat('_',strlen($this->word));            $this->level=$_POST['level'];            $this->misses=0;            $this->setPageState('guessed',null);            // show the guess page            $this->render('guess');        }        else        {            $params=array(                'levels'=>$levels,                // if this is a POST request, it means the level is not chosen                'error'=>Yii::app()->request->isPostRequest,            );            // show the difficulty level page            $this->render('play',$params);        }    }
Obviously, else logic is used. for details, see $ this-> render ('play', $ params). this render method is so familiar that many frameworks have similar methods, for example, discuz, smarty, and CI. throughout the yii Framework, rnder is an important backbone for V implementation in its entire MVC model. So it is necessary to turn it to the bottom of the sky.
This method is available in CController. php:
    public function render($view,$data=null,$return=false)    {        if($this->beforeRender($view))        {            $output=$this->renderPartial($view,$data,true);            if(($layoutFile=$this->getLayoutFile($this->layout))!==false)                $output=$this->renderFile($layoutFile,array('content'=>$output),true);            $this->afterRender($view,$output);            $output=$this->processOutput($output);            if($return)                return $output;            else                echo $output;        }    }

When we echo $ output = $ this-> renderPartial ($ view, $ data, true);, we find that $ output has obtained our final result. The corresponding file is views/game/play. php.

That is what we finally see on index. php. This rendering is relatively simple, so the process of the program is relatively small, but we can see from the source code that a lot of processing is done inside, such as theme or something. This is the first analysis. Good night!




Http://www.bkjia.com/PHPjc/925548.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/925548.htmlTechArticleYII Source Code Analysis (2), yii Source Code Analysis previous a simple analysis of the yii process, from the creation of an application, to the screen output results. This time I come to a slightly more complex, heavy...

Related Article

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.