Yii Source Code Reading Notes

Source: Internet
Author: User
Overview we usually use the template engine to render HTML pages, rather than writing dynamic pages by inserting PHP code in HTML code. In the Yii framework, the template engine is also introduced as a component. The default ID is viewRenderer. However, you can take notes from the Yii source code.

Overview we usually use the template engine to render HTML pages, rather than writing dynamic pages by inserting PHP code in HTML code. In the Yii framework, the template engine is also introduced as a component. The default ID is viewRenderer. However, from the Yii Source Code Reading Notes-component integration, we can see that the core components loaded by the Yii Web application do not include viewRenderer.

Overview

We usually use the template engine to render HTML pages, instead of writing dynamic pages by inserting PHP code in HTML code. In the Yii framework, the template engine is also introduced as a component. The default ID is viewRenderer. However, from the Yii Source Code Reading Notes-component integration, we can see that the core components loaded by the Yii Web application do not include viewRenderer, therefore, you need to configure it yourself. Yii provides a directly available template engine component class CPradoViewRenderer (see the fileyii/framework/web/renderers/CPradoViewRenderer.php). This template engine class allows developers to use the template syntax of the Prado framework class.

If you want to use a third-party template engine like Smarty, there are two ways to introduce the template engine into Yii (using Smarty as an example ):

  1. Encapsulate Smarty into a common Yii component and load the configuration to Yii: app (). If the component ID is smarty, you can useYii::app()->smartyTo call components.
  2. Refer to the implementation of the CPradoViewRenderer class to encapsulate Smarty into a template engine component and load the configuration with the ID as viewRenderer.

In comparison, the second method is better. The reason is: the first method is because the interfaces of each third-party template engine are different. If the application wants to replace the template engine, you need to modify the code in the Controller class. The second method is to encapsulate third-party components in the form of a template engine interface defined by the Yii framework. Therefore, if you want to replace the template engine, you only need to modify the interface Implementation of the Custom template engine component class. In this way, the Code logic for calling the template engine only depends on the interface form, rather than interface implementation, to achieve decoupling.

This article mainly analyzes the implementation of the second method.

Analysis

You can call this method to render the page template in Yii.CControllerClass (See Fileyii/framework/web/CController.php) MethodrenderThe implementation is as follows:

/*** Renders a view with a layout. ** This method first CILS {@ link renderPartial} to render the view (called content view ). * It then renders the layout view which may embed the content view at appropriate place. * In the layout view, the content view rendering result can be accessed via variable *$content. At the end, it cballs {@ link processOutput} to insert scripts * and dynamic contents if they are available. ** By default, the layout view script is "protected/views/layouts/main. php ". * This may be customized by changing {@ link layout }. ** @ param string $ view name of the view to be rendered. see {@ link getViewFile} for details * about how the view script is resolved. * @ param array $ data t O be extracted into PHP variables and made available to the view script * @ param boolean $ return whether the rendering result shocould be returned instead of being displayed to end users. * @ return string the rendering result. null if the rendering result is not required. * @ see renderPartial * @ see getLayoutFile */public function render ($ view, $ data = null, $ return = false) {// beforeRender returns true by default, // Yes This method is rewritten in the Custom controller class to implement preprocessing before rendering. // However, this method is the same as beforeAction, return true or false if ($ this-> beforeRender ($ view) {// render the real content section $ output = $ this-> renderPartial ($ view, $ data, true); // obtain the layout file if ($ layoutFile = $ this-> getLayoutFile ($ this-> layout ))! = False) // render the entire page $ output = $ this-> renderFile ($ layoutFile, array ('content' => $ output), true ); // After rendering, the default value is null. $ this-> afterRender ($ view, $ output) is called before processOutput ); // process the rendering result $ output = $ this-> processOutput ($ output); // you can return the rendering result as the return value of the method, or directly output to the user's browser if ($ return) return $ output; else echo $ output ;}}

The implementation of method renderPartial is as follows:

/*** Renders a view. ** The named view refers to a PHP script (resolved via {@ link getViewFile}) * that is encoded by this method. if $ data is an associative array, * it will be extracted as PHP variables and made available to the script. ** This method differs from {@ link render ()} in that it does not * apply a layout to the rendered result. it is thus mostly used * in rendering a partial view, Or an AJAX response. ** @ param string $ view name of the view to be rendered. see {@ link getViewFile} for details * about how the view script is resolved. * @ param array $ data to be extracted into PHP variables and made available to the view script * @ param boolean $ return whether the rendering result shocould be returned instead of being displayed to end users * @ param boolean $ processOutput Whether the rendering result shocould be postprocessed using {@ link processOutput }. * @ return string the rendering result. null if the rendering result is not required. * @ throws CException if the view does not exist * @ see getViewFile * @ see processOutput * @ see render */public function renderPartial ($ view, $ data = null, $ return = false, $ processOutput = false) {// get the target Template File $ viewFile = $ this-> getViewFile ($ vi Ew); echo (basename (_ FILE __). ':'. _ LINE __. ':'. _ FUNCTION __. '() $ viewfile '. var_export ($ viewFile, true); if ($ viewFile )! = False) {// render $ output = $ this-> renderFile ($ viewFile, $ data, true); // If $ processOutput is true, the results will also be post-processed if ($ processOutput) $ output = $ this-> processOutput ($ output); if ($ return) return $ output; else echo $ output ;} else throw new CException (Yii: t ('yii', '{controller} cannot find the requested view "{view }". ', array (' {controller} '=> get_class ($ this),' {view} '=> $ view )));}

renderPartialThe method does not render a complete page, but only renders a part of the page, usually the main part, or renders the response results for the AJAX request. The getViewFile method is called as follows:

Public function getViewFile ($ viewName) {// if the theme item is not configured, that is, theme is not used, the getTheme method returns null if ($ theme = Yii: app () -> getTheme ())! = Null & ($ viewFile = $ theme-> getViewFile ($ this, $ viewName ))! = False) return $ viewFile; // viewPath is views by default. You can configure $ moduleViewPath = $ basePath = Yii: app ()-> getViewPath (); echo (basename (_ FILE __). ':'. _ LINE __. ':'. _ FUNCTION __. '() $ moduleviewpath '. var_export ($ moduleViewPath, true), "\ n"; // modular. if not, getModule returns null if ($ module = $ this-> getModule ())! = Null) $ moduleViewPath = $ module-> getViewPath (); // $ this-> getViewPath () compared to $ moduleViewPath, the obtained path has an ID-level return $ this-> resolveViewFile ($ viewName, $ this-> getViewPath (), $ basePath, $ moduleViewPath) with the controller parameter );}

Code$this->getViewPath()The method is implemented as follows:

Public function getViewPath () {if ($ module = $ this-> getModule () === null) $ module = Yii: app (); // $ this-> getId () is the ID of the current controller. this ID is assigned to the attribute _ id in the constructor during controller instantiation. // This means that the page template file needs to be stored in the return $ module-> getViewPath (). DIRECTORY_SEPARATOR. $ this-> getId ();} directory according to the controller ID ();}

getViewFileLast called method inresolveViewFileThe implementation is as follows:

Public function resolveViewFile ($ viewName, $ viewPath, $ basePath, $ moduleViewPath = null) {// The template file name is not given, if (empty ($ viewName) return false; // if $ moduleViewPath is not set, find if ($ moduleViewPath = null) $ moduleViewPath = $ basePath; // obtain the preset template rendering engine in the root directory of the application page template, in fact, it is to load the component if ($ renderer = Yii: app ()-> getViewRenderer () with the ID of viewRenderer ())! = Null) // The default extension type of the template file is '. php ', you can configure $ extension = $ renderer-> fileExtension; else $ extension = '. php'; echo (basename (_ FILE __). ':'. _ LINE __. ':'. _ FUNCTION __. '() $ extension '. var_export ($ extension, true), "\ n"; // if the specified template file name starts with/if ($ viewName [0] = '/') {// if the specified template file name starts with //, it indicates that if (strncmp ($ viewName, '//', 2) is searched in the template root directory) === 0) $ viewFile = $ basePath. $ viewName; // otherwise (starting with a single/) Search for else $ viewFile = $ moduleViewPath in the module's template directory. $ ViewName;} // If the template file name exists. and. if the first position does not exist, it is considered as a path alias and the real path elseif (strpos ($ viewName ,'. ') $ viewFile = Yii: getPathOfAlias ($ viewName); else // otherwise, find $ viewFile = $ viewPath in the template directory of the current controller. DIRECTORY_SEPARATOR. $ viewName; // The site may need to be internationalized. // after finding the default template file, try to find the template file if (is_file ($ viewFile. $ extension) return Yii: app ()-> findLocalizedFile ($ viewFile. $ extension); // if no template file of the specified extension type exists and the extension type is not '. php ', let's take a look '. Whether elseif ($ extension! = '. Php '& is_file ($ viewFile. '. php ') return Yii: app ()-> findLocalizedFile ($ viewFile. '. php '); else return false ;}

MethodresolveViewFileLast called method infindLocalizedFileIs defined in the abstract class CApplication. The implementation is as follows:

Public function findLocalizedFile ($ srcFile, $ srcLanguage = null, $ language = null) {if ($ srcLanguage = null) // sourceLanguage is public, configurable, the default value is en_us $ srcLanguage = $ this-> sourceLanguage; if ($ language = null) // Implementation of getLanguage: $ this-> _ language = null? $ This-> sourceLanguage: $ this-> _ language // The default value of _ language is null. Therefore, the value of sourceLanguage is obtained. // But it is also possible to assign values because of _ set. This assignment should not be caused by configuration. It should be based on the language options specified in the user's cookie, when the request is processed, it indicates the user's target language $ language = $ this-> getLanguage (); // if the user's target language (or the user chooses the default language ), return the path of the default template file if ($ language ==$ srcLanguage) return $ srcFile; // otherwise, the template file $ desiredFile = dirname ($ srcFile) in the target language is obtained ). DIRECTORY_SEPARATOR. $ language. DIRECTORY_SEPARATOR.basename ($ srcFile); // If the template file in the target language does not exist, return the default template file return is_file ($ desiredFile )? $ DesiredFile: $ srcFile ;}

From the search process of the preceding template file, we can see that the path of the final returned target template file is a relative path starting with the dynamic script root directory (protected by default.

MethodrenderPartialAfter obtaining the relative path of the target template file, call the renderFile method (defined in the CBaseController class) to render the template. The implementation of this method is as follows:

Public function renderFile ($ viewFile, $ data = null, $ return = false) {$ widgetCount = count ($ this-> _ widgetStack); // Yii: app () -> getViewRenderer () gets the template engine component if ($ renderer = Yii: app ()-> getViewRenderer ())! = Null & $ renderer-> fileExtension = '. '. CFileHelper: getExtension ($ viewFile) $ content = $ renderer-> renderFile ($ this, $ viewFile, $ data, $ return ); else // If the template engine cannot be used for rendering (it may not be the target template of the template engine or the template engine component is not set ), the current normal PHP file (HTML code is mixed with PHP Code) to 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 have an endWidget () call. ', array (' {controller} '=> get_class ($ this),' {view} '=> $ viewFile, '{widget}' => get_class ($ widget ))));}}

renderFileMedium$content=$renderer->renderFile($this,$viewFile,$data,$return);The renderFile method called by one row is defined in the abstract class CViewRenderer as follows:

Public function renderFile ($ context, $ sourceFile, $ data, $ return) {if (! Is_file ($ sourceFile) | ($ file = realpath ($ sourceFile) === false) throw new CException (Yii: t ('yii ', 'view file "{file}" does not exist. ', array (' {file} '=> $ sourceFile); // try to get the compiled template from the runtime directory, if the compiled template is not stored in the runtime directory, the template file and the uncompiled template file are stored in the same directory by default, and the file name has one more "c" suffix // $ viewFile may not exist. The first request for this template $ viewFile = $ this-> getViewFile ($ sourceFile ); // If the uncompiled template file has changed compared to the compiled template file, re-compile the template file. // If the compiled template file does not exist, @ filemtime ($ viewFile) false is returned. This condition also returns true if (@ filemtime ($ sourceFile)> @ filemtime ($ viewFile) {// The generateViewFile method in the abstract class CViewRenderer is not implemented, therefore, you need to implement this method when encapsulating the template engine component by yourself $ this-> generateViewFile ($ sourceFile, $ viewFile); // set the access permission for the compiled template file, the default value is 0755 (owner rwx, group rx and others rx) @ chmod ($ viewFile, $ this-> filePermission );} // The compiled template file is actually a PHP script (HTML code is mixed with PHP code), so you also need to render return $ context-> renderInternal ($ viewFile, $ data, $ return );}

ClassCControllerOfrenderThe method is calledrenderPartialAfter obtaining the rendering result, obtain the page layout template file, and thenrenderPartialAs a Data Rendering layout template to obtain a complete HTML page. How to obtain the layout template file pathgetLayoutFileThe implementation is as follows (defined in class CController ):

Public function getLayoutFile ($ layoutName) {if ($ layoutName = false) return false; if ($ theme = Yii: app ()-> getTheme ())! = Null & ($ layoutFile = $ theme-> getLayoutFile ($ this, $ layoutName ))! = False) return $ layoutFile; if (empty ($ layoutName) {$ module = $ this-> getModule (); // recursively query the layout file for the parent template while ($ module! = Null) {if ($ module-> layout = false) return false; if (! Empty ($ module-> layout) break; $ module = $ module-> getParentModule ();} // if the current controller does not belong to a module if ($ module = null) $ module = Yii: app (); // The default value is main, you can configure $ layoutName = $ module-> layout;} elseif ($ module = $ this-> getModule () = null) $ module = Yii :: app (); return $ this-> resolveViewFile ($ layoutName, $ module-> getLayoutPath (), Yii: app ()-> getViewPath (), $ module-> getViewPath ());}

Its logic and MethodgetViewFileSimilar.

From the above analysis, we can see that the third-party template engine is encapsulated into the template engine component of the Yii framework and can inherit from the abstract class.CViewRendererAnd implement the MethodgenerateViewFileAnd then configure the component IDviewRenderer. For the storage of template files, you need to consider whether the Web application is divided into modules, whether the application is internationalized, And the template file-related controller ID. The extension type of the template file name should be the same as the template engine component configuration.

Original article address: Yii Source Code Reading Notes-template engine integration, thanks to the original author for sharing.

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.