PHP程序员站--PHP编程开发平台
 当前位置:主页 >> PHP开源 >> PHP开源框架 >> 

Yii中文手册

Yii中文手册

来源:phperz.com  作者:phperz.com  发布时间:2011-12-01
Yii framework 中文手册 Yii 是什么 Yii 是一个基于组件、用于开发大型 Web 应用的高性能 PHP 框架。它将 Web 编程中的可重用性发挥到极致,能够显著加速开发进程。Yii(读作易)代表简单(easy)、高效(efficient)、可扩展(extensible)。 需求 要运行一个基于 Yii 开发

Data Types(数据类型)

当定义的方法和属性被远程访问,我们需要指定输入和输出参数的数据类型。以下的原始数据类型可以使用:

·        str/string: 对应 xsd:string;

·        int/integer: 对应 xsd:int;

·        float/double: 对应 xsd:float;

·        bool/boolean: 对应 xsd:boolean;

·        date: 对应 xsd:date;

·        time: 对应 xsd:time;

·        datetime: 对应 xsd:dateTime;

·        array: 对应 xsd:string;

·        object: 对应 xsd:struct;

·        mixed: 对应 xsd:anyType.

如果类型不属于上述任何原始类型,它被看作是复合型组成的属性。复合型类型被看做类,他的属性当做类的公有成员变量,在文档注释中被用@soap标记。

我们还可以使用数组类型通过附加[]在原始或复合型类型的后面。这将定义指定类型的数组。

下面就是一个例子定义getPosts网页API,返回一个Post对象的数组。

class PostController extends CController

{

    /**

     * @return Post[] a list of posts

     * @soap

     */

    public function getPosts()

    {

        return Post::model()->findAll();

    }

}

 

class Post extends CActiveRecord

{

    /**

     * @var integer post ID

     * @soap

     */

    public $id;

    /**

     * @var string post title

     * @soap

     */

    public $title;

}

Class Mapping(类映射)

为了从客户端得到复合型参数,应用程序需要定义从WSDL类型到相应PHP类的映射。这是通过配置CWebServiceAction的属性classMap。

class PostController extends CController

{

    public function actions()

    {

        return array(

            'service'=>array(

                'class'=>'CWebServiceAction',

                'classMap'=>array(

                    'Post'=>'Post',  // or simply 'Post'

                ),

            ),

        );

    }

    ......

}

Intercepting Remote Method Invocation(拦截远程方法调用)

通过实现IWebServiceProvider接口,sevice provider可以拦截远程方法调用。在 IWebServiceProvider::beforeWebMethod ,sevice provider可以获得当前CWebService实例和通过CWebService::methodName请求的方法的名字 。它可以返回假如果远程方法出于某种原因不应被援引(例如:未经授权的访问) 。

 

Internationalization

Internationalization (I18N) refers to the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. For Web applications, this is of particular importance because the potential users may be from worldwide.

Yii provides support for I18N in several aspects.

·        It provides the locale data for each possible language and variant.

·        It provides message and file translation service.

·        It provides locale-dependent date and time formatting.

·        It provides locale-dependent number formatting.

In the following subsections, we will elaborate each of the above aspects.

Locale and Language

Locale is a set of parameters that defines the user's language, country and any special variant preferences that the user wants to see in their user interface. It is usually identified by an ID consisting of a language ID and a region ID. For example, the ID en_US stands for the locale of English and United States. For consistency, all locale IDs in Yii are canonicalized to the format of LanguageID or LanguageID_RegionID in lower case (e.g. en, en_us).

Locale data is represented as a CLocale instance. It provides locale-dependent information, including currency symbols, number symbols, currency formats, number formats, date and time formats, and date-related names. Since the language information is already implied in the locale ID, it is not provided by CLocale. For the same reason, we often interchangeably using the term locale and language.

Given a locale ID, one can get the corresponding CLocale instance by CLocale::getInstance($localeID) or CApplication::getLocale($localeID).

Info: Yii comes with locale data for nearly every language and region. The data is obtained from Common Locale Data Repository (CLDR). For each locale, only a subset of the CLDR data is provided as the original data contains a lot of rarely used information. Starting from version 1.1.0, users can also supply their own customized locale data. To do so, configure the CApplication::localeDataPath property with the directory that contains the customized locale data. Please refer to the locale data files under framework/i18n/data in order to create customized locale data files.

For an Yii application, we differentiate its target language from source language. The target language is the language (locale) of the users that the application is targeted at, while the source language refers to the language (locale) that the application source files are written in. Internationalization occurs only when the two languages are different.

One can configure target language in the application configuration, or change it dynamically before any internationalization occurs.

Tip: Sometimes, we may want to set the target language as the language preferred by a user (specified in user's browser preference). To do so, we can retrieve the user preferred language ID using CHttpRequest::preferredLanguage.

Translation

The most needed I18N feature is perhaps translation, including message translation and view translation. The former translates a text message to the desired language, while the latter translates a whole file to the desired language.

A translation request consists of the object to be translated, the source language that the object is in, and the target language that the object needs to be translated to. In Yii, the source language is default to the application source language while the target language is default to the application language. If the source and target languages are the same, translation will not occur.

Message Translation

Message translation is done by calling Yii::t(). The method translates the given message from source language to target language.

When translating a message, its category has to be specified since a message may be translated differently under different categories (contexts). The category yii is reserved for messages used by the Yii framework core code.

Messages can contain parameter placeholders which will be replaced with the actual parameter values when calling Yii::t(). For example, the following message translation request would replace the {alias} placeholder in the original message with the actual alias value.

Yii::t('yii', 'Path alias "{alias}" is redefined.',

    array('{alias}'=>$alias))

Note: Messages to be translated must be constant strings. They should not contain variables that would change message content (e.g. "Invalid {$message} content."). Use parameter placeholders if a message needs to vary according to some parameters.

Translated messages are stored in a repository called message source. A message source is represented as an instance of CMessageSource or its child class. When Yii::t() is invoked, it will look for the message in the message source and return its translated version if it is found.

Yii comes with the following types of message sources. You may also extend CMessageSource to create your own message source type.

·        CPhpMessageSource: the message translations are stored as key-value pairs in a PHP array. The original message is the key and the translated message is the value. Each array represents the translations for a particular category of messages and is stored in a separate PHP script file whose name is the category name. The PHP translation files for the same language are stored under the same directory named as the locale ID. And all these directories are located under the directory specified by basePath.

·        CGettextMessageSource: the message translations are stored as GNU Gettext files.

·        CDbMessageSource: the message translations are stored in database tables. For more details, see the API documentation for CDbMessageSource.

A message source is loaded as an application component. Yii pre-declares an application component named messages to store messages that are used in user application. By default, the type of this message source is CPhpMessageSource and the base path for storing the PHP translation files is protected/messages.

In summary, in order to use message translation, the following steps are needed:

1.      Call Yii::t() at appropriate places;

2.      Create PHP translation files as protected/messages/LocaleID/CategoryName.php. Each file simply returns an array of message translations. Note, this assumes you are using the default CPhpMessageSource to store the translated messages.

3.      Configure CApplication::sourceLanguage and CApplication::language.

Tip: The yiic tool in Yii can be used to manage message translations when CPhpMessageSource is used as the message source. Its message command can automatically extract messages to be translated from selected source files and merge them with existing translations if necessary.

Starting from version 1.0.10, when using CPhpMessageSource to manage message source, messages for an extension class (e.g. a widget, a module) can be specially managed and used. In particular, if a message belongs to an extension whose class name is Xyz, then the message category can be specified in the format of Xyz.categoryName. The corresponding message file will be assumed to be BasePath/messages/LanguageID/categoryName.php, where BasePath refers to the directory that contains the extension class file. And when using Yii::t() to translate an extension message, the following format should be used, instead:

Yii::t('Xyz.categoryName', 'message to be translated')

Since version 1.0.2, Yii has added the support for choice format. Choice format refers to choosing a translated according to a given number value. For example, in English the word 'book' may either take a singular form or a plural form depending on the number of books, while in other languages, the word may not have different form (such as Chinese) or may have more complex plural form rules (such as Russian). Choice format solves this problem in a simple yet effective way.

To use choice format, a translated message must consist of a sequence of expression-message pairs separated by |, as shown below:

'expr1#message1|expr2#message2|expr3#message3'

where exprN refers to a valid PHP expression which evaluates to a boolean value indicating whether the corresponding message should be returned. Only the message corresponding to the first expression that evaluates to true will be returned. An expression can contain a special variable named n (note, it is not $n) which will take the number value passed as the first message parameter. For example, assuming a translated message is:

'n==1#one book|n>1#many books'

and we are passing a number value 2 in the message parameter array when calling Yii::t(), we would obtain many books as the final translated message.

As a shortcut notation, if an expression is a number, it will be treated as n==Number. Therefore, the above translated message can be also be written as:

'1#one book|n>1#many books'

File Translation

File translation is accomplished by calling CApplication::findLocalizedFile(). Given the path of a file to be translated, the method will look for a file with the same name under the LocaleID subdirectory. If found, the file path will be returned; otherwise, the original file path will be returned.

File translation is mainly used when rendering a view. When calling one of the render methods in a controller or widget, the view files will be translated automatically. For example, if the target language is zh_cn while the source language is en_us, rendering a view named edit would resulting in searching for the view file protected/views/ControllerID/zh_cn/edit.php. If the file is found, this translated version will be used for rendering; otherwise, the file protected/views/ControllerID/edit.php will be rendered instead.

File translation may also be used for other purposes, for example, displaying a translated image or loading a locale-dependent data file.

Date and Time Formatting

Date and time are often in different formats in different countries or regions. The task of date and time formatting is thus to generate a date or time string that fits for the specified locale. Yii provides CDateFormatter for this purpose.

Each CDateFormatter instance is associated with a target locale. To get the formatter associated with the target locale of the whole application, we can simply access the dateFormatter property of the application.

The CDateFormatter class mainly provides two methods to format a UNIX timestamp.

·        format: this method formats the given UNIX timestamp into a string according to a customized pattern (e.g. $dateFormatter->format('yyyy-MM-dd',$timestamp)).

·        formatDateTime: this method formats the given UNIX timestamp into a string according to a pattern predefined in the target locale data (e.g. short format of date, long format of time).

Number Formatting

Like data and time, numbers may also be formatted differently in different countries or regions. Number formatting includes decimal formatting, currency formatting and percentage formatting. Yii provides CNumberFormatter for these tasks.

To get the number formatter associated with the target locale of the whole application, we can access the numberFormatter property of the application.

The following methods are provided by CNumberFormatter to format an integer or double value.

·        format: this method formats the given number into a string according to a customized pattern (e.g. $numberFormatter->format('#,##0.00',$number)).

·        formatDecimal: this method formats the given number using the decimal pattern predefined in the target locale data.

·        formatCurrency: this method formats the given number and currency code using the currency pattern predefined in the target locale data.

·        formatPercentage: this method formats the given number using the percentage pattern predefined in the target locale data.

 

Using Alternative Template Syntax
Yii allows developers to use their own favorite template syntax (e.g. Prado, Smarty) to write controller or widget views. This is achieved by writing and installing a viewRenderer application component. The view renderer intercepts the invocations of CBaseController::renderFile, compiles the view file with customized template syntax, and renders the compiling results.

Info: It is recommended to use customized template syntax only when writing views that are less likely to be reused. Otherwise, people who are reusing the views would be forced to use the same customized template syntax in their applications.

In the following, we introduce how to use CPradoViewRenderer, a view renderer that allows developers to use the template syntax similar to that in Prado framework. For people who want to develop their own view renderers, CPradoViewRenderer is a good reference.

Using CPradoViewRenderer
To use CPradoViewRenderer, we just need to configure the application as follows:

return array(
    'components'=>array(
        ......,
        'viewRenderer'=>array(
            'class'=>'CPradoViewRenderer',
        ),
    ),
);
By default, CPradoViewRenderer will compile source view files and save the resulting PHP files under the runtime directory. Only when the source view files are changed, will the PHP files be re-generated. Therefore, using CPradoViewRenderer incurs very little performance degradation.

Tip: While CPradoViewRenderer mainly introduces some new template tags to make writing views easier and faster, you can still write PHP code as usual in the source views.

In the following, we introduce the template tags that are supported by CPradoViewRenderer.

Short PHP Tags
Short PHP tags are shortcuts to writing PHP expressions and statements in a view. The expression tag <%= expression %> is translated into <?php echo expression ?>; while the statement tag <% statement %> to <?php statement ?>. For example,

<%= CHtml::textField($name,'value'); %>
<% foreach($models as $model): %>
is translated into

<?php echo CHtml::textField($name,'value'); ?>
<?php foreach($models as $model): ?>
Component Tags
Component tags are used to insert a widget in a view. It uses the following syntax:

<com:WidgetClass property1=value1 property2=value2 ...>
    // body content for the widget
</com:WidgetClass>
 
// a widget without body content
<com:WidgetClass property1=value1 property2=value2 .../>
where WidgetClass specifies the widget class name or class path alias, and property initial values can be either quoted strings or PHP expressions enclosed within a pair of curly brackets. For example,

<com:CCaptcha captchaAction="captcha" showRefreshButton={false} />
would be translated as

<?php $this->widget('CCaptcha', array(
    'captchaAction'=>'captcha',
    'showRefreshButton'=>false)); ?>
Note: The value for showRefreshButton is specified as {false} instead of "false" because the latter means a string instead of a boolean.

Cache Tags
Cache tags are shortcuts to using fragment caching. Its syntax is as follows,

<cache:fragmentID property1=value1 property2=value2 ...>
    // content being cached
</cache:fragmentID >
where fragmentID should be an identifier that uniquely identifies the content being cached, and the property-value pairs are used to configure the fragment cache. For example,

<cache:profile duration={3600}>
    // user profile information here
</cache:profile >
would be translated as

<?php if($this->cache('profile', array('duration'=>3600))): ?>
    // user profile information here
<?php $this->endCache(); endif; ?>
Clip Tags
Like cache tags, clip tags are shortcuts to calling CBaseController::beginClip and CBaseController::endClip in a view. The syntax is as follows,

<clip:clipID>
    // content for this clip
</clip:clipID >
where clipID is an identifier that uniquely identifies the clip content. The clip tags will be translated as

<?php $this->beginClip('clipID'); ?>
    // content for this clip
<?php $this->endClip(); ?>
Comment Tags
Comment tags are used to write view comments that should only be visible to developers. Comment tags will be stripped off when the view is displayed to end users. The syntax for comment tags is as follows,

<!---
view comments that will be stripped off
--->
 

Console Applications
Console applications are mainly used by a Web application to perform offline work, such as code generation, search index compiling, email sending, etc. Yii provides a framework for writing console applications in an object-oriented and systematic way.

Yii represents each console task in terms of a command, and a console application instance is used to dispatch a command line request to an appropriate command. The application instance is created in an entry script. To execute a console task, we simply run the corresponding command on the command line as follows,

php entryScript.php CommandName Param0 Param1 ...
where CommandName refers to the command name which is case-insensitive, and Param0, Param1 and so on are parameters to be passed to the command instance.

The entry script for a console application is usually written like the following, similar to that in a Web application,

defined('YII_DEBUG') or define('YII_DEBUG',true);
// include Yii bootstrap file
require_once('path/to/yii/framework/yii.php');
// create application instance and run
$configFile='path/to/config/file.php';
Yii::createConsoleApplication($configFile)->run();
We then create command classes which should extend from CConsoleCommand. Each command class should be named as its command name appended with Command. For example, to define an email command, we should write an EmailCommand class. All command class files should be placed under the commands subdirectory of the application base directory.

Tip: By configuring CConsoleApplication::commandMap, one can also have command classes in different naming conventions and located in different directories.

Writing a command class mainly involves implementing the CConsoleCommand::run method. Command line parameters are passed as an array to this method. Below is an example:

class EmailCommand extends CConsoleCommand
{
    public function run($args)
    {
        $receiver=$args[0];
        // send email to $receiver
    }
}
At any time in a command, we can access the console application instance via Yii::app(). Like a Web application instance, console application can also be configured. For example, we can configure a db application component to access the database. The configuration is usually specified as a PHP file and passed to the constructor of the console application class (or createConsoleApplication in the entry script).

Using the yiic Tool
We have used the yiic tool to create our first application. The yiic tool is in fact implemented as a console application whose entry script file is framework/yiic.php. Using yiic, we can accomplish tasks such as creating a Web application skeleton, generating a controller class or model class, generating code needed by CRUD operations, extracting messages to be translated, etc.

We can enhance yiic by adding our own customized commands. To do so, we should start with a skeleton application created using yiic webapp command, as described in Creating First Yii Application. The yiic webapp command will generate two files under the protected directory: yiic and yiic.bat. They are the local version of the yiic tool created specifically for the Web application.

We can then create our own commands under the protected/commands directory. Running the local yiic tool, we will see that our own commands appearing together with the standard ones. We can also create our own commands to be used when yiic shell is used. To do so, just drop our command class files under the protected/commands/shell directory.

 

安全措施 (Security)

跨站脚本攻击的防范

跨站脚本攻击(简称 XSS),即web应用从用户收集用户数据。攻击者常常向易受攻击的web应用注入JavaScript,VBScript,ActiveX,HTML或 Flash来迷惑访问者以收集访问者的信息。举个例子,一个未经良好设计的论坛系统可能不经检查就显示用户所输入的内容。攻击者可以在帖子内容中注入一段恶意的JavaScript代码。这样,当其他访客在阅读这个帖子的时候,这些JavaScript代码就可以在访客的电脑上运行了。

一个防范XSS攻击的最重要的措施之一就是:在显示用户输入的内容之前进行内容检查。比如,你可以对内容中的HTML进行转义处理。但是在某些情况下这种方法就不可取了,因为这种方法禁用了所有的HTML标签。

Yii集成了HTMLPurifier并且为开发者提供了一个很有用的组件CHtmlPurifier,这个组件封装了HTMLPurifier类。它可以将通过有效的审查、安全和白名单功能来把所审核的内容中的所有的恶意代码清除掉,并且确保过滤之后的内容过滤符合标准。

CHtmlPurifier组件可以作为一个widget或者filter来使用。当作为一个widget来使用的时候,CHtmlPurifier可以对在视图中显示的内容进行安全过滤。以下是代码示例:

<?php $this->beginWidget('CHtmlPurifier'); ?>

//...这里显示用户输入的内容...

<?php $this->endWidget(); ?>

跨站请求伪造攻击的防范

跨站请求伪造(简称CSRF)攻击,即攻击者在用户浏览器在访问恶意网站的时候,让用户的浏览器向一个受信任的网站发起攻击者指定的请求。举个例子,一个恶意网站有一个图片,这个图片的src地址指向一个银行网站: http://bank.example/withdraw?transfer=10000&to=someone。如果用户在登陆银行的网站之后访问了这个恶意网页,那么用户的浏览器会向银行网站发送一个指令,这个指令的内容可能是“向攻击者的帐号转账10000元”。跨站攻击方式利用用户信任的某个特定网站,而CSRF攻击正相反,它利用用户在某个网站中的特定用户身份。

要防范CSRF攻击,必须谨记一条:GET请求只允许检索数据而不能修改服务器上的任何数据。而POST请求应当含有一些可以被服务器识别的随机数值,用来保证表单数据的来源和运行结果发送的去向是相同的。

Yii实现了一个CSRF防范机制,用来帮助防范基于POST的攻击。这个机制的核心就是在cookie中设定一个随机数据,然后把它同表单提交的POST数据中的相应值进行比较。

默认情况下,CSRF防范是禁用的。如果你要启用它,可以编辑应用配置 中的组件中的CHttpRequest部分。

代码示例:

return array(

    'components'=>array(

        'request'=>array(

            'enableCsrfValidation'=>true,

        ),

    ),

);

要显示一个表单,请使用CHtml::form而不要自己写HTML代码。因为CHtml::form可以自动地在表单中嵌入一个隐藏项,这个隐藏项储存着验证所需的随机数据,这些数据可在表单提交的时候发送到服务器进行验证。

Cookie攻击的防范

保护cookie免受攻击是非常重要的。因为session ID通常存储在Cookie中。如果攻击者窃取到了一个有效的session ID,他就可以使用这个session ID对应的session信息。

这里有几条防范对策:

·        您可以使用SSL来产生一个安全通道,并且只通过HTTPS连接来传送验证cookie。这样攻击者是无法解密所传送的cookie的。

·        设置cookie的过期时间,对所有的cookie和seesion令牌也这样做。这样可以减少被攻击的机会。

·        防范跨站代码攻击,因为它可以在用户的浏览器触发任意代码,这些代码可能会泄露用户的cookie。

·        在cookie有变动的时候验证cookie的内容。

Yii实现了一个cookie验证机制,可以防止cookie被修改。启用之后可以对cookie的值进行HMAC检查。

Cookie验证在默认情况下是禁用的。如果你要启用它,可以编辑应用配置 中的组件中的CHttpRequest部分。

代码示例:

return array(

    'components'=>array(

        'request'=>array(

            'enableCookieValidation'=>true,

        ),

    ),

);

一定要使用经过Yii验证过的cookie数据。使用Yii内置的cookies组件来进行cookie操作,不要使用$_COOKIES。

// 检索一个名为$name的cookie值

$cookie=Yii::app()->request->cookies[$name];

$value=$cookie->value;

......

// 设置一个cookie

$cookie=new CHttpCookie($name,$value);

Yii::app()->request->cookies[$name]=$cookie;

 

Performance Tuning

Performance of Web applications is affected by many factors. Database access, file system operations, network bandwidth are all potential affecting factors. Yii has tried in every aspect to reduce the performance impact caused by the framework. But still, there are many places in the user application that can be improved to boost performance.

Enabling APC Extension

Enabling the PHP APC extension is perhaps the easiest way to improve the overall performance of an application. The extension caches and optimizes PHP intermediate code and avoids the time spent in parsing PHP scripts for every incoming request.

Disabling Debug Mode

Disabling debug mode is another easy way to improve performance. An Yii application runs in debug mode if the constant YII_DEBUG is defined as true. Debug mode is useful during development stage, but it would impact performance because some components cause extra burden in debug mode. For example, the message logger may record additional debug information for every message being logged.

Using yiilite.php

When the PHP APC extension is enabled, we can replace yii.php with a different Yii bootstrap file named yiilite.php to further boost the performance of an Yii-powered application.

The file yiilite.php comes with every Yii release. It is the result of merging some commonly used Yii class files. Both comments and trace statements are stripped from the merged file. Therefore, using yiilite.php would reduce the number of files being included and avoid execution of trace statements.

Note, using yiilite.php without APC may actually reduce performance, because yiilite.php contains some classes that are not necessarily used in every request and would take extra parsing time. It is also observed that using yiilite.php is slower with some server configurations, even when APC is turned on. The best way to judge whether to use yiilite.php or not is to run a benchmark using the included hello world demo.

Using Caching Techniques

As described in the Caching section, Yii provides several caching solutions that may improve the performance of a Web application significantly. If the generation of some data takes long time, we can use the data caching approach to reduce the data generation frequency; If a portion of page remains relatively static, we can use the fragment caching approach to reduce its rendering frequency; If a whole page remains relative static, we can use the page caching approach to save the rendering cost for the whole page.

If the application is using Active Record, we should turn on the schema caching to save the time of parsing database schema. This can be done by configuring the CDbConnection::schemaCachingDuration property to be a value greater than 0.

Besides these application-level caching techniques, we can also use server-level caching solutions to boost the application performance. As a matter of fact, the APC caching we described earlier belongs to this category. There are other server techniques, such as Zend Optimizer, eAccelerator, Squid, to name a few.

Database Optimization

Fetching data from database is often the main performance bottleneck in a Web application. Although using caching may alleviate the performance hit, it does not fully solve the problem. When the database contains enormous data and the cached data is invalid, fetching the latest data could be prohibitively expensive without proper database and query design.

Design index wisely in a database. Indexing can make SELECT queries much faster, but it may slow down INSERT, UPDATE or DELETE queries.

For complex queries, it is recommended to create a database view for it instead of issuing the queries inside the PHP code and asking DBMS to parse them repetitively.

Do not overuse Active Record. Although Active Record is good at modelling data in an OOP fashion, it actually degrades performance due to the fact that it needs to create one or several objects to represent each row of query result. For data intensive applications, using DAO or database APIs at lower level could be a better choice.

Last but not least, use LIMIT in your SELECT queries. This avoids fetching overwhelming data from database and exhausting the memory allocated to PHP.

Minimizing Script Files

Complex pages often need to include many external JavaScript and CSS files. Because each file would cause one extra round trip to the server and back, we should minimize the number of script files by merging them into fewer ones. We should also consider reducing the size of each script file to reduce the network transmission time. There are many tools around to help on these two aspects.

For a page generated by Yii, chances are that some script files are rendered by components that we do not want to modify (e.g. Yii core components, third-party components). In order to minimizing these script files, we need two steps.

Note: The scriptMap feature described in the following has been available since version 1.0.3.

First, we declare the scripts to be minimized by configuring the scriptMap property of the clientScript application component. This can be done either in the application configuration or in code. For example,

$cs=Yii::app()->clientScript;

$cs->scriptMap=array(

    'jquery.js'=>'/js/all.js',

    'jquery.ajaxqueue.js'=>'/js/all.js',

    'jquery.metadata.js'=>'/js/all.js',

    ......

);

What the above code does is that it maps those JavaScript files to the URL /js/all.js. If any of these JavaScript files need to be included by some components, Yii will include the URL (once) instead of the individual script files.

Second, we need to use some tools to merge (and perhaps compress) the JavaScript files into a single one and save it as js/all.js.

The same trick also applies to CSS files.

We can also improve page loading speed with the help of Google AJAX Libraries API. For example, we can include jquery.js from Google servers instead of our own server. To do so, we first configure the scriptMap as follows,

$cs=Yii::app()->clientScript;

$cs->scriptMap=array(

    'jquery.js'=>false,

    'jquery.ajaxqueue.js'=>false,

    'jquery.metadata.js'=>false,

    ......

);

By mapping these script files to false, we prevent Yii from generating the code to include these files. Instead, we write the following code in our pages to explicitly include the script files from Google,

<head>

<?php echo CGoogleApi::init(); ?>

 

<?php echo CHtml::script(

    CGoogleApi::load('jquery','1.3.2') . "\n" .

    CGoogleApi::load('jquery.ajaxqueue.js') . "\n" .

    CGoogleApi::load('jquery.metadata.js')

); ?>

......

</head>


延伸阅读:
Yii是什么
Tags: Yii   中文手册   手册  
最新文章
推荐阅读
月点击排行榜
PHP程序员站 Copyright © 2007-2010,PHPERZ.COM All Rights Reserved 粤ICP备07503606号