Analysis of the usage of the self-contained front-end resource bundle for YII framework in PHP

Source: Internet
Author: User
Tags aliases php class php source code yii
This article mainly introduces the use of the front-end resource bundle in the YII framework of PHP, enumerates some JavaScript and CSS resources commonly used in yii, and needs friends to refer to the following

The resources in Yii are files related to Web pages, which can be called by the Web server, such as CSS files, javascript files, pictures or videos, and resources placed in a Web accessible directory.

It's a little better to manage resources automatically through programs, for example, when you use the Yii\jui\datepicker widget on a page, it automatically contains the CSS and JavaScript files you need, rather than asking you to manually find the files and include them when you upgrade the widgets. It will automatically use the new version of the resource file, and in this tutorial we will dwell on the powerful resource management capabilities that YII provides.

Resource bundle

Yii manages resources in a resource bundle, a resource bundle is simply a collection of resources placed in a directory, and when a resource bundle is registered in a view, the CSS and JavaScript files in the package are included when the Web page is rendered.

Defining Resource Bundles

The resource bundle is specified as a PHP class that inherits Yii\web\assetbundle, the package name is a PHP class name that can be loaded automatically, and in the resource bundle class, you specify the location of the resource, which CSS and JavaScript files are included, and the dependencies that are related to the other packages.

The following code defines the primary resource bundle used by the underlying app 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\bo Otstrapasset ',];}

As the Appasset class specifies that the resource file is placed in the @webroot directory, the corresponding URL is @web, the resource bundle contains a CSS file Css/site.css, no JavaScript file, dependent on the other two packages Yii\web\yiiasset and Yii\bootstrap\bootstrapasset, more details on the properties of Yii\web\assetbundle are described below:

    • Yii\web\assetbundle::sourcepath: Specifies that the package contains the root directory of the resource file, which should be set when the root directory cannot be accessed by the web, otherwise the Yii\web\assetbundle::basepath property should be set and yii\ Web\assetbundle::baseurl. Path aliases can be used here;

    • Yii\web\assetbundle::basepath: Specifies a directory that contains resource files in the resource bundle and can be accessed by the Web, when the Yii\web\assetbundle::sourcepath property is specified, the resource Manager Will publish the package's resources to a web-accessible and overwrite this property, and if your resource file is in a Web-accessible directory, you should set the property so that it doesn't have to be published anymore. Path aliases can be used here.

Yii\web\assetbundle::baseurl: Specifies the URL corresponding to the Yii\web\assetbundle::basepath directory, similar to Yii\web\assetbundle::basepath, If you specify the Yii\web\assetbundle::sourcepath property, the resource manager publishes the resources and overrides the attribute, where the path alias can be used.
Yii\web\assetbundle::js: An array containing the resource bundle JavaScript files, note that the forward slash "/" should be used as the directory delimiter, and 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), and the actual path of the file is preceded by the relative path with Yii\web\assetmanager::basepath, and the actual URL of the file is preceded by the path yii\web\ Assetmanager::baseurl.

    • An absolute URL address is represented as an external JavaScript file, such as 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 resource bundle JavaScript file, which is in the same format as YII\WEB\ASSETBUNDLE::JS.

    • Yii\web\assetbundle::d epends: An additional resource bundle that lists the resource bundle dependencies (described in more detail in the next two sections).

    • Yii\web\assetbundle::jsoptions: Specifies the option to pass to this method when calling Yii\web\view::registerjsfile () to register each JavaScript file for the package.

    • Yii\web\assetbundle::cssoptions: Specifies the option to pass to the method when Yii\web\view::registercssfile () is called to register each CSS file for the package.

    • Yii\web\assetbundle::p ublishoptions: When calling Yii\web\assetmanager::p ublish () publishes the package resource file to the Web directory when specifying the option to pass to the method, only when the yii\web\ is specified The Assetbundle::sourcepath property is used.

Resource Location

Depending on their location, resources can be divided into:

SOURCE resources: Resource files and PHP source code together, cannot be directly accessed by the Web, in order to use these source resources, they are copied to a Web-accessible web directory to become a published resource, this process is known as publishing resources, which are described in detail later.
Publish resource: The resource file is placed in a web directory that can be accessed directly through the web;
External resources: Resource files are placed on different Web servers of your Web application;
When you define a resource bundle class, if you specify the Yii\web\assetbundle::sourcepath property, any resource that uses a relative path is treated as a source resource, and if the attribute is not specified, it means that the resource is a publishing resource (so you should specify Yii\web\ Assetbundle::basepath and Yii\web\assetbundle::baseurl let Yii know where they are.

It is recommended that you put the resource file in the Web directory to avoid unnecessary publishing of the resource process, which is the previous example specifying Yii\web\assetbundle::basepath instead of Yii\web\assetbundle::sourcepath.

For extensions, the Yii\web\assetbundle::sourcepath property must be specified when defining a resource bundle class, because both their resources and source code are in directories that cannot be accessed by the Web.

Note: The Yii\web\assetbundle::sourcepath property does not use @webroot/assets, which defaults to the path that Yii\web\assetmanager resource Manager will store resources after it is published. All contents of the path are considered temporary files and may be deleted.
Resource dependency

When a Web page contains multiple CSS or JavaScript files, they have a certain order of precedence to avoid property overrides, for example, Web pages must ensure that jquery JavaScript files are included before using the jquery UI widget. We call this resource prioritization called resource dependency.

Resource dependencies are specified primarily through the Yii\web\assetbundle::d Epends property, in the Appasset example, the resource bundle relies on the other two resource bundles: Yii\web\yiiasset and Yii\bootstrap\ Bootstrapasset the CSS and JavaScript files for this resource bundle are included only after the files of the two dependent packages are included.

Resource dependencies are transitive, that is, people say a relies on b,b C, then a also relies on C.

Resource Options

You can specify the Yii\web\assetbundle::cssoptions and Yii\web\assetbundle::jsoptions properties to customize how the page contains CSS and JavaScript files, which are passed to yii\ The Web\view::registercssfile () and Yii\web\view::registerjsfile () methods are called when the view calls these methods to contain CSS and JavaScript files.

Note: The options set in the resource pack class apply to each Css/javascript file in the package, and if you want to use different options for each file, you should create a different resource bundle and use an option set in each package.
For example, a browser that only wants to IE9 or higher contains a CSS file that can use the following options:

Public $cssOptions = [' condition ' = ' LTE IE9 '];

This will be the CSS file in the package that is included with the following HTML tags:

<!--[If LTE ie9]><link rel= "stylesheet" href= "Path/to/foo.css" ><! [endif]-->

The following code is used to include <noscript> for the link label:

Public $cssOptions = [' noscript ' = ' = True];

To include the JavaScript file in the page Head area (the JavaScript file is included by default at the end of the body), use the following options:

Public $jsOptions = [' Position ' = \yii\web\view::P os_head];

Bower and NPM Resources

Most JAVASCRIPT/CSS packages are managed by bower and/or NPM, and if your app or extension uses these packages, it is recommended that you follow these steps to manage resources in the library:

Modify the application or extension of the Composer.json file to include the package in require, use the Bower-asset/packagename (Bower package) or Npm-asset/packagename (NPM package) to correspond to the library.
Create a resource bundle class and include the Javascript/css file you want to use with your app or extension in your class, set the Yii\web\assetbundle::sourcepath property to @bower/packagename or @npm/ PackageName, because the alias composer installs the Bower or NPM package to the corresponding directory.
Note: Some packages place their distributed files in a subdirectory, in which case you should specify a subdirectory as the Yii\web\assetbundle::sourcepath property value, for example, Yii\web\jqueryasset use @bower/ Jquery/dist rather than @bower/jquery.
Using Resource Bundles

To use a resource bundle, call the Yii\web\assetbundle::register () method in the view to register the resource first, for example, in a view template to register a resource bundle with the following code:

Use App\assets\appasset; Appasset::register ($this); $this represents a View object

If you register a resource bundle elsewhere, you should provide a view object, such as registering a resource bundle in a widget class, and you can get the View object by $this->view.

When registering a resource bundle in the view, Yii registers the resource bundle on which it depends, and if the resource bundle is placed in a directory that is inaccessible to the web, it will be published to the accessible directory, and subsequent when the view renders the page, the corresponding < of the CSS and JavaScript files contained in these registration packages will be generated. Link> and <script> tags, the order of the tags depends on the dependency of the resource bundle and the order in which the YII\WEB\ASSETBUNDLE::CSS and Yii\web\assetbundle::js are listed.

Custom Resource Bundles

Yii implements [[Yii\web\assetmanager] to manage application components through an application component named Assetmanager, which allows you to customize the behavior of a resource bundle by configuring the Yii\web\assetmanager::bundles property, for example, The Yii\web\jqueryasset resource bundle uses the Jquery.js file from the jquery Bower package by default, and you may need to obtain the jquery file from your Google server for increased availability and performance. You can configure Assetmanager in the app configuration as follows:

return [//... ' Components ' = [' Assetmanager ' + [' bundles ' = ' = ' yii\web\jqueryasset ' and '    = '     SourcePath ' + NULL,//must not publish the resource     ' js ' and ' =      '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/ Jquery.min.js ',     ]]    ,   ], [  ],],];

Multiple resource bundles can be configured through similar yii\web\assetmanager::bundles, where the key of the array should be the class name of the resource bundle (the first not the backslash), and the value of the array is the corresponding configuration array.

Tip: You can determine which resource to use based on the criteria, as an example of how to use jquery.js in a development environment, otherwise use jquery.min.js:

' Yii\web\jqueryasset ' = [' js ' and ' =  Yii_env_dev? ' Jquery.js ': ' Jquery.min.js '],

You can set the name of the resource bundle to False to disable one or more resource bundles that you want to disable, and when a view registers a disabled resource bundle, the view does not contain any resources for that package and does not register the packages that it depends on, for example, to disable Yii\web\jqueryasset, you can use the following configuration:

return [//... ' Components ' = [' Assetmanager ' + ['   bundles ' = ' = '    yii\web\jqueryasset ' and false,   ],  ], ],];

You can set Yii\web\assetmanager::bundles to False to disable all resource bundles.

Resource deployment

Sometimes you want to "fix" the error/incompatibility of resource files in multiple resource bundles, such as package a using the 1.11.1 version of Jquery.min.js, Package B uses the 2.1.1 version of Jquery.js to customize each package to solve this problem, and the better way is to use the resource Deployment feature to deploy the incorrect resources for the desired, and to do this, configure the Yii\web\assetmanager::assetmap property as follows:

return [//... ' Components ' = [' Assetmanager ' + [' assetmap ' = ' = ' jquery.js ' and '   = '    //ajax.googleapis.com/ Ajax/libs/jquery/2.1.1/jquery.min.js ',   ],  [],],];

The Yii\web\assetmanager::assetmap key is the resource name that you want to fix, the value is the resource path that you want to use, and when the view registers the resource bundle, the YII\WEB\ASSETBUNDLE::CSS and Yii\web\assetbundle :: Each dependent resource file in the JS array is compared to the deployment, and if any of the keys in the array are compared to the last file name of the resource file (prefixed with Yii\web\assetbundle::sourcepath if any), the corresponding value is the replacement of the original resource. For example, the resource file My/path/to/jquery.js matches the key jquery.js.

Note: Only the resources specified relative to relative paths correspond to the resource deployment, the replacement resource path can be an absolute path, or it can be a path related to Yii\web\assetmanager::basepath.
Resource release

As mentioned earlier, if the resource bundle is placed in a directory that the Web cannot access, the resource is copied to a Web-accessible directory when the view registers the resource, a process called a resource release, and Yii\web\assetmanager automatically handles the process.

Resources are published by default to the @webroot/assets directory, with the corresponding URL @web/assets, configurable Yii\web\assetmanager::basepath and Yii\web\assetmanager::baseurl property to customize the publishing location.

In addition to copying files to publish resources, this feature can be enabled by setting Yii\web\assetmanager::linkassets to True if the operating system and Web server allow symbolic links to be used.

return [//... ' Components ' = [  ' assetmanager ' = ' = '   linkassets ' + True,  ],],;

With the above configuration, the resource Manager creates a symbolic link to the source path of the resource bundle to be published, which is faster than copying files and ensures that the published resources are always up to date.

Common Resource Packs

The YII framework defines many resource bundles, the following resource bundles are most commonly used, and can be referenced in your app or extension code.

    • Yii\web\yiiasset: Mainly contains the Yii.js file, which completes the module JavaScript code organization function, also provides special support and other useful functions for Data-method and DATA-CONFIRM attributes.

    • Yii\web\jqueryasset: Contains the Jquery.js file from the jquery Bower package.

    • Yii\bootstrap\bootstrapasset: Contains CSS files from the Twitter bootstrap framework.

    • Yii\bootstrap\bootstrappluginasset: Contains JavaScript files from the Twitter bootstrap framework to support bootstrap JavaScript plugins.

    • Yii\jui\juiasset: Contains CSS and JavaScript files from the jquery UI library.

If your code requires jquery, jquery UI, or Bootstrap, you should try to use these predefined resource bundles instead of creating them yourself, and if the default configuration of these packages does not meet your needs, you can customize the configuration, and refer to the custom Resource pack for details.

Resource Conversion

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

Resource files that use the extended syntax can be listed in the YII\WEB\ASSETBUNDLE::CSS and Yii\web\assetbundle::js of the resource bundle as follows:

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 registering a resource bundle in a view, the Yii\web\assetmanager Resource Manager automatically runs the preprocessing tool to convert resources that use the extended syntax to Css/javascript, which is included in the page when the view eventually renders the page css/ The Javascipt file, rather than the original extension syntax code file.

Yii uses the file extension to indicate which extension syntax is used by the resource, and the following syntax and file name extensions are recognized by default:

    • Less:.

    • SCSS:. SCSS

    • Stylus:. Styl

    • Coffeescript:. Coffee

    • TypeScript:. ts

Yii relies on the pre-processing tools installed to convert resources, for example, to use less, you should install the LESSC preprocessing command.

You can configure the Yii\web\assetmanager::converter custom preprocessing command and the supported extension syntax as follows:

return [' components ' + = [' Assetmanager ' and ' = '   converter ' and ' = '    class ' = ' yii\web\ Assetconverter ',    ' commands ' = = [     ' Less ' = [' css ', ' LESSC {from} {to}--no-color '],     ' ts ' = = [' js ', ' TSC--out {to} {from} '],    ],   [],  ],],];

As shown above, the supported extension syntax is specified by the Yii\web\assetconverter::commands property, the key of the array is the file extension (not the previous.), the value of the array is the target resource file name extension and the command that performs the resource conversion, the tag {from} and the {to } will be replaced by the source resource file path and the target resource file path, respectively.

Add: In addition to the above, there are other ways to handle the extension syntax resources, for example, you can use the compilation tools such as grunt to monitor and automatically convert the extension syntax resources, at this time, the resource bundle should use the compiled Css/javascript file instead of the original file.
Merging and compressing resources

A Web page can contain a lot of CSS and/or JavaScript files, in order to reduce the size of HTTP requests and these download files, the usual way is to merge and compress multiple Css/javascript files into one or few files in the page, and use the compressed file instead of the original file.

Add: Merging and compressing resources are often applied in the product-on-line mode, and using the original Css/javascript in development mode is more convenient to debug.
The next step is to introduce a way to merge and compress resource files without modifying the existing code:

Find all the resource bundles in your app that you want to merge and compress,
Divide the packages into one or several groups, noting that each package can belong to only one of the groups.
Merging/compressing CSS files in each group into a file, and processing JavaScript files in the same way,
Define a new resource bundle for each group:
Set the Yii\web\assetbundle::css and Yii\web\assetbundle::js properties for the compressed CSS and JavaScript files, respectively;
Custom Set the resource bundle within each group, set the Yii\web\assetbundle::css and Yii\web\assetbundle::js properties of the resource bundle to NULL, and set their yii\web\assetbundle::d epends Property is a newly created resource bundle for each group.
In this way, when a resource bundle is registered in a view, the registration of the group Resource bundle to which the original package belongs is automatically triggered, and then the page contains the resource file to merge/compress instead of the original file.

Example

Use an example to explain the above approach:

Identify your app with two pages x and Y, page x using resource bundles A, B and C, page Y using resource packs b,c and D.

There are two ways to divide these resource bundles, one is to use one group to contain all the resource bundles, the other is to put (A,B,C) in Group X, (b,c,c) in group Y, which way is better? The first advantage is that 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 the files, the merged CSS and Javascipt files will be larger, thus increasing the file transfer time, in this example, We use the first method, which is to include all the packages in one group.

Add: Grouping resource bundles is not worthless and often requires analyzing the amount of data on different pages of a real-world page, starting with a single group for ease of use.
Using tools (such as Closure Compiler, YUI Compressor) in all packages to merge and compress CSS and JavaScript files, note that the merged file satisfies the successive dependencies between packages, for example, if package a relies on b,b dependencies C and D, Then the list of resource files starts with C and D, and then B ends with a.

After merging and compressing, you get a CSS file and a JavaScript file, assuming they are named All-xyz.css and All-xyz.js, XYZ is the timestamp or hash value that makes the file name unique to avoid HTTP caching issues.

Now to the last step, configure the Yii\web\assetmanager Explorer in the app configuration as follows:

return [' components ' + = [' Assetmanager ' + [' bundles ' = ' = ' all ' and ' = '     class ' = ' Yii\we B\assetbundle ',     ' basepath ' = ' @webroot/assets ',     ' baseUrl ' = ' and ' @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 Pack section, the configuration changes the default behavior for each package, especially if packages A, B, C, and D no longer contain any resource files, they all depend on the package all that contains the merged all-xyz.css and all-xyz.js files, so For page x, this will include the two merged files instead of the original files for package A, B, C, and for page Y.

Finally, there is a way to better handle the above method, in addition to directly modify the application configuration file, you can put a custom package array into a file, in the application configuration according to the criteria to include the file, for example:

return [' components ' + = [' Assetmanager ' and ' = '   bundles ' + require (__dir__. '/' . (Yii_env_prod?) ' assets-prod.php ': ' assets-dev.php '),], [],]   ;

As shown above, in the product launch mode, the resource bundle array is stored in the assets-prod.php file, not the product on-line mode stored in the assets-dev.php file.

Using the Asset command

YII provides a console command called asset to automatically process the above operations.

To use this command, create a profile to set which resource bundles to merge and how to group them, use the ASSET/TEMPLATE subcommand 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, which resembles the following:

<?php/** * configuration file for console command "Yii Asset" * Note that in the console environment, some path aliases such as ' @webroot ' and ' @web ' will not exist * Please define a path alias that does not exist */return [//For Javascrip T file compression modified Command/callback  ' jscompressor ' = ' Java-jar Compiler.jar--js {from}--js_output_file {to} ',//for CSS file compression Modify Command/callback  ' csscompressor ' = ' Java-jar Yuicompressor.jar--type css {from}-o {to} ',//List of resource bundles to compress ' bundle s ' = = [  //' Yii\web\yiiasset ',  //' Yii\web\jqueryasset ',],//resource pack after compression output ' targets ' = [' all ' = ' =  
   ' class ' = ' Yii\web\assetbundle ',   ' basepath ' and ' @webroot/assets ',   ' baseUrl ' = ' @web/assets ',   ' js ' = ' js/all-{hash}.js ',   ' css ' = ' css/all-{hash}.css ',  ],],//Explorer configuration: ' Assetmanager ' + [] ,];

You should modify the bundles option of the file to specify which packages you want to merge, and in the targets option you should specify how these packages are grouped, as described above, to specify one or more groups.

Note: Because aliases @webroot and @web are not available in the console, they should be explicitly specified in the configuration.
JavaScript files are compressed and then written to the Js/all-{hash}.js file, where {hash} is replaced by the hash value of the resulting file.

The Jscompressor and Csscompressor options specify console commands or PHP callback functions to perform JavaScript and CSS merging and compression, and Yii uses closure compiler to merge JavaScript files by default, using Yui Compressor to merge CSS files, you should manually install these tools or modify the options using the tools you like.

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

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

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.