Detailed description of the use of the frontend resource package in the Yii Framework of PHP _ PHP

Source: Internet
Author: User
Tags file url
This article mainly introduces the use of front-end resource packages in the PHP Yii Framework, and lists some common JavaScript and CSS resources in Yii, for more information, see Yii. the resources are files related to Web pages. they can be CSS files, JavaScript files, images or videos. the resources are stored in accessible Web directories, directly called by the Web server.

It is better to use programs to automatically manage resources. for example, when you use the yii \ jui \ DatePicker widget on the page, it automatically contains the required CSS and JavaScript files, instead of requiring you to manually find and include these files, when you upgrade the widget, it will automatically use the new version of the resource file. in this tutorial, we will detail the powerful resource management functions provided by Yii.

Resource Package

Yii manages resources in the resource package. In short, the resource package is a resource set placed in a directory. when a resource package is registered in the view, when rendering a Web page, the CSS and JavaScript files in the package are included.

Define a resource package

The resource package is specified as the PHP class that inherits yii \ web \ AssetBundle. the package name is the PHP class name that can be automatically loaded. in the resource package class, you must specify the resource location, which CSS and JavaScript files are contained and their dependencies with other packages.

The following code defines the main resource packages used by the basic application template:

<?phpnamespace app\assets;use yii\web\AssetBundle;class AppAsset extends AssetBundle{ public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [  'css/site.css', ]; public $js = [ ]; public $depends = [  'yii\web\YiiAsset',  'yii\bootstrap\BootstrapAsset', ];}

In the above AppAsset class, the specified resource file is placed in the @ webroot directory, and the corresponding URL is @ web. the resource package contains a CSS file css/site.css with no JavaScript file, dependent on the other two packages yii \ web \ YiiAsset and yii \ bootstrap \ BootstrapAsset. For more details about the attributes of yii \ web \ AssetBundle, refer to the following:

  • Yii \ web \ AssetBundle: sourcePath: specifies the root directory of the package containing resource files. this attribute should be set when the root directory cannot be accessed by the Web. otherwise, set the yii \ web \ AssetBundle: basePath attribute and yii \ web \ AssetBundle: baseUrl. The path alias can be used here;
  • Yii \ web \ AssetBundle: basePath: specifies the directory that contains Chinese source files in the resource package and is accessible to the Web. when the yii \ web \ AssetBundle: sourcePath attribute is specified, the resource manager will release the package resources to a Web-accessible and overwrite this attribute. if your resource file is in a Web-accessible directory, set this attribute, in this way, you do not need to release any more. The path alias can be used here.

Yii \ web \ AssetBundle: baseUrl: specify the URL corresponding to the yii \ web \ AssetBundle: basePath directory, which is similar to yii \ web \ AssetBundle: basePath, if you specify the yii \ web \ AssetBundle: sourcePath attribute, the resource manager will publish these resources and overwrite the attributes. The path alias can be used here.
Yii \ web \ AssetBundle: js: an array containing the JavaScript file of the resource package. Note that the forward slash "/" should be used as the directory separator, each JavaScript file can be specified as one of the following two formats:

  • The relative path is represented as a local JavaScript file (such as js/main. js). add yii \ web \ AssetManager: basePath to the actual file path, and add yii \ web \ AssetManager: baseUrl to the actual file URL.
  • The absolute URL address is represented as an external JavaScript file, such as a http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js or // ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js.
  • Yii \ web \ AssetBundle: css: an array containing the JavaScript file of the resource package. the array format is the same as that of yii \ web \ AssetBundle: js.
  • Yii \ web \ AssetBundle: depends: other resource packages that list the dependencies of the resource package (the last two sections will be described in detail ).
  • Yii \ web \ AssetBundle: jsOptions: specifies the option to pass to this method when you call yii \ web \ View: registerJsFile () to register each JavaScript file of this package.
  • Yii \ web \ AssetBundle: cssOptions: specifies the option to pass to this method when you call yii \ web \ View: registerCssFile () to register each css file of this package.
  • Yii \ web \ AssetBundle: publishOptions: specifies the option to pass to this method when you call yii \ web \ AssetManager: publish () to publish the package resource file to the Web Directory, it is used only when the yii \ web \ AssetBundle: sourcePath attribute is specified.

Resource Location

Resources can be divided:

SOURCE Resources: resource files and PHP source code are put together and cannot be directly accessed by the Web. to use these source resources, they must be copied to a Web directory that can be accessed by the Web to become published resources, this process is called a release resource and will be detailed later.
Publish resources: Place resource files in a Web directory that can be directly accessed through the Web;
External Resources: resource files are stored on different Web servers of your Web applications;
When defining a resource package, if you specify the yii \ web \ AssetBundle: sourcePath attribute, it means that any resource using the relative path will be treated as the source resource. if this attribute is not specified, it indicates that these resources are published resources (therefore, you should specify yii \ web \ AssetBundle: basePath and yii \ web \ AssetBundle: baseUrl to let Yii know their location ).

We recommend that you put the resource file in the Web directory to avoid unnecessary resource Publishing. this is the previous example specifying yii \ web \ AssetBundle: basePath instead of yii \ web \ AssetBundle: sourcePath.

For extensions, because their resources and source code are in a directory that cannot be accessed by the Web, you must specify the yii \ web \ AssetBundle: sourcePath attribute when defining the resource package class.

Note: Do not use @ webroot/assets for the yii \ web \ AssetBundle: sourcePath attribute. the default path is the path where the source resource is stored after the yii \ web \ AssetManager resource manager releases the source resource, all contents of the path are considered as temporary files and may be deleted.
Resource dependency

When a Web page contains multiple CSS or JavaScript files, they have a certain order to avoid attribute overwriting. for example, before using jQuery UI widgets, Web pages must ensure that jQuery JavaScript files are included. We call this resource order resource dependency.

Resource Dependencies are mainly specified through the yii \ web \ AssetBundle: depends attribute. in the AppAsset example, the resource package depends on the other two resource packages: yii \ web \ YiiAsset and yii \ bootstrap \ BootstrapAsset are the CSS and JavaScript files of the resource package, which must be included only after the files of the two dependent packages are included.

Resource dependency is interchangeable, that is, if A depends on B and B depends on C, A also depends on C.

Resource options

You can specify the yii \ web \ AssetBundle: cssOptions and yii \ web \ AssetBundle: jsOptions attributes to customize how the page contains CSS and JavaScript files, these attribute values are passed to the yii \ web \ View: registerCssFile () and yii \ web \ View: registerJsFile () methods respectively, when the View calls these methods to include CSS and JavaScript files.

Note: the options set in the resource package class will be applied to each CSS/JavaScript file in the package. if you want to use different options for each file, different resource packages should be created and an option set should be used in each package.
For example, if you only want IE9 or a higher browser to contain a CSS file, you can use the following options:

public $cssOptions = ['condition' => 'lte IE9'];

This will include the CSS file in the package using the following HTML tags:

 

Include You can use the following code:

public $cssOptions = ['noscript' => true];

Use the following options to include a JavaScript file in the header area of the page (the JavaScript file is included at the end of the body by default:

public $jsOptions = ['position' => \yii\web\View::POS_HEAD];

Bower and NPM resources

Most JavaScript/CSS packages are managed through Bower and/or NPM. if your applications or extensions use these packages, we recommend that you follow these steps to manage resources in the library:

Modify the application or extended composer. json file to include the package in require. use bower-asset/PackageName (Bower package) or npm-asset/PackageName (NPM package) to correspond to the library.
Create a resource package class and include the JavaScript/CSS file to be used by your application or extension into the class. set yii \ web \ AssetBundle :: the sourcePath attribute is @ bower/PackageName or @ npm/PackageName, because the Bower or NPM package is installed in the corresponding directory according to the alias Composer.
Note: Some packages place their distributed files in a sub-directory. in this case, specify the sub-directory as the yii \ web \ AssetBundle: sourcePath attribute value, for example, yii \ web \ JqueryAsset use @ bower/jquery/dist instead of @ bower/jquery.
Use Resource Package

To use the resource package, call the yii \ web \ AssetBundle: register () method in the view to register the resource first. for example, you can use the following code to register the resource package in the view template:

Use app \ assets \ AppAsset; AppAsset: register ($ this); // $ this indicates the View object

If you register a resource package elsewhere, you should provide a view object. for example, if you register a resource package in the widget class, you can use $ this-> view to obtain the view object.

When registering a resource package in the view, Yii will register the resource package on which it depends. if the resource package is placed in a directory inaccessible to the Web, it will be published to an accessible directory, when the view renders the page in the future, these registration packages will generate the corresponding CSS and JavaScript files And script tags. The order of these tags depends on the dependencies between the resource package and the dependencies between yii \ web \ AssetBundle: css and yii \ web \ AssetBundle :: the order of js columns.

Custom resource package

Yii uses the application component named assetManager to implement [[yii \ web \ AssetManager] to manage application components. by configuring the yii \ web \ AssetManager: bundles attribute, Yii can customize the behavior of resource packages, for example, the yii \ web \ JqueryAsset resource package uses jquery by default from the jquery Bower package. to improve availability and performance, you may need to obtain the jquery file from the Google server. you can configure assetManager in the application configuration, as shown below:

Return [//... 'components' => ['assetmanager' => ['bundle' => ['yii \ web \ jqueryasset' => ['sourcepath '=> null, // do not publish this resource 'js' => ['// ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',],];

You can configure multiple resource packages using a command similar to yii \ web \ AssetManager: bundles. the key of the array should be the class name of the resource package (do not backslash at the beginning ), the value of the array is the corresponding configuration array.

Tip: you can determine which resource to use based on the conditions. The following example shows how to use jquery. js in the development environment. otherwise, jquery. min. js is used:

'yii\web\JqueryAsset' => [ 'js' => [  YII_ENV_DEV ? 'jquery.js' : 'jquery.min.js' ]],

You can set the resource package name to false to disable one or more resource packages you want to disable. when a disabled resource package is registered in the view, the view does not contain any resources of the package and does not register the packages it depends on. for example, to disable yii \ web \ JqueryAsset, you can use the following configuration:

return [ // ... 'components' => [  'assetManager' => [   'bundles' => [    'yii\web\JqueryAsset' => false,   ],  ], ],];

You can set yii \ web \ AssetManager: bundles to false to disable all resource packages.

Resource deployment

Sometimes you want to "fix" errors/incompatibility of Chinese source files in multiple resource packages. for example, package A uses jquery of version 1.11.1. min. js. Package B uses jquery 2.1.1. js, you can customize each package to solve this problem. The better way is to use the resource deployment feature to deploy incorrect resources as desired. Therefore, configure yii \ web \ AssetManager :: the assetMap attribute is as follows:

return [ // ... 'components' => [  'assetManager' => [   'assetMap' => [    'jquery.js' => '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',   ],  ], ],];

Yii \ web \ AssetManager: Key of assetMap: name of the resource you want to repair, value: Path of the resource you want to use. when the view registers a resource package, in yii \ web \ AssetBundle :: css and yii \ web \ AssetBundle: each related resource file in the js array will be compared with the deployment, if any key in the array is compared to the final file name of the resource file (if any, the prefix is yii \ web \ AssetBundle: sourcePath), the corresponding value is to replace the original resource. For example, the resource file my/path/to/jquery. js matches the key jquery. js.

Note: Only resources specified in relative paths correspond to resource deployment. the replaced resource path can be an absolute path or a path related to yii \ web \ AssetManager: basePath.
Resource release

As mentioned above, if the resource package is placed in a directory inaccessible to the Web, when the view registers the resource, the resource will be copied to a Web accessible directory. this process is called resource release, yii \ web \ AssetManager automatically processes the process.

Resources are published to the @ webroot/assets directory by default. the corresponding URL is @ web/assets. you can configure yii \ web \ AssetManager: basePath and yii \ web \ AssetManager :: customize the publishing location of the baseUrl attribute.

In addition to copying files to publish resources, if the operating system and the Web server allow the use of symbolic links, this function can be enabled by setting yii \ web \ AssetManager: linkAssets to true.

return [ // ... 'components' => [  'assetManager' => [   'linkAssets' => true,  ], ],];

With the above configuration, the resource manager will create a symbolic link to the source path of the resource package to be released, which is faster than copying files and ensures that the released resources are always the latest.

Common resource packages

The Yii Framework defines many Resource Packages. the following resource packages are the most commonly used and can be referenced in your application or extension code.

  • Yii \ web \ YiiAsset: mainly includes yii. js file, which completes the JavaScript code organization function of the module. It also provides special support and other useful functions for the data-method and data-confirm attributes.
  • Yii \ web \ JqueryAsset: contains the jQuery. js file from the jquery bower package.
  • Yii \ bootstrap \ BootstrapAsset: contains the CSS file from the Twitter Bootstrap framework.
  • Yii \ bootstrap \ BootstrapPluginAsset: contains JavaScript files from the Twitter Bootstrap framework to support the Bootstrap JavaScript plug-in.
  • Yii \ jui \ JuiAsset: contains CSS and JavaScript files from the jQuery UI Library.

If your code requires jQuery, jQuery UI, or Bootstrap, try to use these predefined resource packages instead of those created by yourself. if the default configurations of these packages cannot meet your needs, you can customize the configuration. For more information, see custom resource packages.

Resource conversion

In addition to writing CSS and/or JavaScript code directly, developers often use the extended syntax and use special tools to convert them into CSS/Javascript. For example, you can use LESS or SCSS for CSS code and TypeScript for JavaScript code.

You can list the resource files that use the extended syntax to yii \ web \ AssetBundle: css and yii \ web \ AssetBundle: js of the resource package, as shown below:

class AppAsset extends AssetBundle{ public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [  'css/site.less', ]; public $js = [  'js/site.ts', ]; public $depends = [  'yii\web\YiiAsset',  'yii\bootstrap\BootstrapAsset', ];}

When you register such a resource package in the view, the yii \ web \ AssetManager Resource Manager automatically runs the preprocessing tool to convert resources using the extended syntax to CSS/JavaScript, when a View finally renders a page, the page contains the CSS/Javascipt file instead of the original extension syntax code file.

Yii uses the file extension to indicate which extension syntax the resource uses. by default, the following syntax and file extension can be identified:

  • LESS:. less
  • SCSS:. scss
  • Stylus:. styl
  • CoffeeScript:. coffee
  • TypeScript:. ts

Yii relies on the pre-processing tool installed to convert resources. for example, to use LESS, the lessc pre-processing command should be installed.

You can configure yii \ web \ AssetManager: converter to customize preprocessing commands and supported extended syntaxes, as shown below:

return [ 'components' => [  'assetManager' => [   'converter' => [    'class' => 'yii\web\AssetConverter',    'commands' => [     'less' => ['css', 'lessc {from} {to} --no-color'],     'ts' => ['js', 'tsc --out {to} {from}'],    ],   ],  ], ],];

As shown above, you can use the yii \ web \ AssetConverter: commands attribute to specify the supported extension syntax. the array key is the file extension (not mentioned earlier .), the value of the array is the extension of the target resource file and the command for executing resource conversion. the {from} and {to} in the command are replaced by the source resource file path and the target resource file path respectively.

Supplement: in addition to the preceding methods, there are other methods to process extended syntax resources. for example, you can use a compilation tool such as grunt to monitor and automatically convert extended syntax resources, use the compiled CSS/Javascript file in the resource package instead of the original file.
Merge and compress resources

A Web page can contain many CSS and/or JavaScript files. to reduce HTTP requests and the size of these downloaded files, the common method is to merge and compress multiple CSS/JavaScript files into one or a few files on the page, and use the compressed file instead of the original file.

Supplement: Merging and compressing resources is usually used in the product launch mode. in the development mode, the original CSS/JavaScript is used to facilitate debugging.
Next we will introduce a method to merge and compress resource files without modifying existing code:

Find the resource packages you want to merge and compress in the application,
Divide these packages into one or several groups. Note that each package can belong to only one group,
Merge/compress CSS files in each group to one file, and process JavaScript files in the same way,
Define a new resource package for each group:
Set the yii \ web \ AssetBundle: css and yii \ web \ AssetBundle: js attributes to the compressed CSS and JavaScript files respectively;
Set the resource package in each group and set the yii \ web \ AssetBundle: css and yii \ web \ AssetBundle: js attributes of the resource package to null, set their yii \ web \ AssetBundle: depends attributes to the newly created resource package for each group.
In this way, when a resource package is registered in the view, the registration of the group resource package to which the original package belongs is automatically triggered. then, the page contains the merged/compressed resource files, instead of the original file.

Example

An example is provided to illustrate the preceding method:

Verify that your application has two pages X and Y. page X uses resource packages A, B, and C, and page Y uses resource packages B, C, and D.

There are two ways to divide these resource packages, one is to use A group to contain all the resource packages, the other is to put (A, B, C) in group X, (B, C, C) in group Y, which method is better? The first method has the advantage that the two pages use the same merged CSS and JavaScript files to make the HTTP cache more efficient. on the other hand, because a single group contains all files, the merged CSS and Javascipt files are larger, so the file transfer time is increased. In this example, we use the first method, that is, to include all the packages in a group.

Supplement: grouping resource packages is not worthless. it is usually necessary to analyze the data volume of various resources on different pages in reality and use a group easily at the beginning.
Use tools (such as Closure Compiler and YUI Compressor) in all packages to merge and compress CSS and JavaScript files. Note that the merged files satisfy the successive dependencies between Packages. for example, if Package A depends on B, B depends on C and D, the list of resource files starts with C and D, and then B ends with.

After merging and compressing, a cssfile and a JavaScript file are generated, which is called all-xyz.css and all-xyz.js, and xyz is the timestamp or hash value that uniquely makes the file name to avoid HTTP cache problems.

Now, in the last step, configure the yii \ web \ AssetManager resource manager in the application configuration as follows:

return [ 'components' => [  'assetManager' => [   'bundles' => [    'all' => [     'class' => 'yii\web\AssetBundle',     'basePath' => '@webroot/assets',     'baseUrl' => '@web/assets',     'css' => ['all-xyz.css'],     'js' => ['all-xyz.js'],    ],    'A' => ['css' => [], 'js' => [], 'depends' => ['all']],    'B' => ['css' => [], 'js' => [], 'depends' => ['all']],    'C' => ['css' => [], 'js' => [], 'depends' => ['all']],    'D' => ['css' => [], 'js' => [], 'depends' => ['all']],   ],  ], ],];

As described in the custom Resource Package section, the above configuration changes the default behavior of each package, especially the package a% B %cand ddoes not include any resource files, are all dependent on the package of the integrated all-xyz.css and all-xyz.js file, so, for page X that will contain the merged files instead of the original files of packages A, B, and C, the same applies to page Y.

Finally, there is a way to better deal with the above method. in addition to directly modifying the application configuration file, you can put the custom package array into a file and include the file in the application configuration according to the conditions. for example:

return [ 'components' => [  'assetManager' => [   'bundles' => require(__DIR__ . '/' . (YII_ENV_PROD ? 'assets-prod.php' : 'assets-dev.php')),   ], ],];

As shown above, resource package arrays are stored in assets-prod.php files in product launch mode, not in product launch mode stored in assets-dev.php files.

Use the asset command

Yii provides an asset Console Command to automatically process the preceding operations.

To use this command, you should first create a configuration file to set the resource packages to be merged and grouping methods. you can use the asset/template sub-command to generate a template and then modify the template to what you want.

yii asset/template assets.php

This command generates a file named assets. php in the current directory. the file content is similar to the following:

<? Php/*** is the configuration file used by the console command "yii asset" * Note that in the console environment, some path aliases such as '@ webroot' and' @ Web' do not exist * define a nonexistent path alias */return [// modify command/callback 'jscompressor '= for JavaScript file compression> 'Java-jar compiler. jar -- js {from} -- js_output_file {to} ', // modify command/callback 'csscompressor' => 'Java-jar yuicompressor for CSS file compression. jar -- type css {from}-o {to} ', // Resource Package List to be compressed 'bundle' => [// 'yii \ web \ yiiasset ', // 'yii \ web \ jqueryasset',], // output 'targets' => ['all' => ['class' => 'yii \ web \ assetbundle' after the resource package is compressed ', 'basepath' => '@ webroot/assets', 'baseurl' => '@ web/assets', 'js' => 'JS/all-{hash }. JS', 'css '=> 'css/all-javashash=.css',],], // resource manager configuration: 'assetmanager' => [],];

Modify the bundles option of the file to specify which packages you want to merge, and specify how to group these packages in the targets option. for example, you can specify one or more groups.

Note: Because the application Alias @ webroot and @ web is unavailable on the console, you should specify them in the configuration.
JavaScript files are merged and compressed and written to the js/all-{hash}. js file. {hash} is replaced by the hash value of the result file.

The jsCompressor and cssCompressor options specify console commands or PHP callback functions to execute JavaScript and CSS merge and compression. Yii uses Closure Compiler by default to merge JavaScript files and YUI Compressor to merge CSS files, you should manually install these tools or modify options to use your preferred tools.

Depending on the configuration file, you can execute the asset command to merge and compress the resource file and generate a new resource package configuration file assets-prod.php:

Yii asset assets. php config/assets-prod.php

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.