Describes how to use the frontend resource package in the Yii framework of PHP.

Source: Internet
Author: User
Tags file url php source code

Describes how to use the frontend resource package in the Yii framework of PHP.

Yii resources are files related to Web pages. They can be CSS files, JavaScript files, images or videos. Resources are placed in accessible Web directories and directly called by Web servers.

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:

<!--[if lte IE9]><link rel="stylesheet" href="path/to/foo.css"><![endif]-->

Use the following code to include a link tag <noscript>:

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, the <link> and <script> labels corresponding to the CSS and JavaScript files contained in these registration packages will be generated, the order of these tags depends on the dependency between the resource package and the order listed in yii \ web \ AssetBundle: css and yii \ web \ AssetBundle: js.

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

Articles you may be interested in:
  • Introduction to some advanced usage of cache in PHP Yii framework
  • In-depth analysis of the cache function in the PHP Yii framework
  • Advanced View usage in PHP Yii framework
  • Detailed description of how to create and render views in the Yii framework of PHP
  • PHP Yii framework Model learning tutorial
  • Detailed explanation of Controller in PHP Yii framework
  • How to remove the behavior bound to a component from the Yii framework of PHP
  • Definition and binding of behavior in PHP Yii framework
  • In-depth explanation of attributes in PHP Yii framework)
  • Detailed description of PHP Yii framework extension Installation and Use

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.