Home Backend Development PHP Tutorial Detailed explanation of the use of front-end resource packages in PHP's Yii framework_php skills

Detailed explanation of the use of front-end resource packages in PHP's Yii framework_php skills

May 16, 2016 pm 07:55 PM
css javascript php yii

Resources in Yii are files related to Web pages, which can be CSS files, JavaScript files, images or videos, etc. The resources are placed in a directory accessible to the Web and are directly called by the Web server.

It is better to automatically manage resources through programs. For example, when you use the yiijuiDatePicker widget in a page, it will automatically include the required CSS and JavaScript files, instead of requiring you to manually find these files and include them. When you upgrade a 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 Pack

Yii manages resources in resource packages. Resource packages are simply a collection of resources placed in a directory. When a resource package is registered in a view, the CSS and JavaScript files in the package will be included when rendering the web page.

Define resource package

The resource package is designated as a PHP class that inherits yiiwebAssetBundle. The package name is a PHP class name that can be automatically loaded. In the resource package class, you need to specify the location of the resource, which CSS and JavaScript files it contains, and its dependencies with other packages.

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

<&#63;php

namespace 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',
 ];
}

Copy after login

As above, the resource file specified by the AppAsset class is placed in the @webroot directory, and the corresponding URL is @web. The resource package contains a CSS file css/site.css, no JavaScript file, and relies on the other two packages yiiwebYiiAsset and yiibootstrapBootstrapAsset. About More details on the properties of yiiwebAssetBundle are described below:

  • yiiwebAssetBundle::sourcePath: Specifies the root directory of the bundle containing resource files. This property should be set when the root directory cannot be accessed by the Web. Otherwise, the yiiwebAssetBundle::basePath property and yiiwebAssetBundle::baseUrl should be set. Path aliases can be used here;
  • yiiwebAssetBundle::basePath: Specifies the directory that contains the resource files in the resource bundle and is Web-accessible. When specifying the yiiwebAssetBundle::sourcePath attribute, the resource manager will publish the resources of the package to a Web-accessible directory and override this attribute. If you If the resource file is in a Web-accessible directory, this attribute should be set so that it does not need to be published again. Path aliases can be used here.

yiiwebAssetBundle::baseUrl: Specifies the URL corresponding to the yiiwebAssetBundle::basePath directory. Similar to yiiwebAssetBundle::basePath, if you specify the yiiwebAssetBundle::sourcePath attribute, the resource manager will publish these resources and override this attribute. The path alias can be used here.
yiiwebAssetBundle::js: An array containing the JavaScript files of the resource bundle. Note that the forward slash "/" should be used as the directory separator. Each JavaScript file can be specified in one of the following two formats:

  • The relative path is represented as a local JavaScript file (such as js/main.js). The actual path of the file is preceded by yiiwebAssetManager::basePath. The actual URL of the file is preceded by yiiwebAssetManager::baseUrl.
  • Absolute URL addresses are represented as external JavaScript files, 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.
  • yiiwebAssetBundle::css: An array containing the JavaScript files of the resource bundle. The array format is the same as yiiwebAssetBundle::js.
  • yiiwebAssetBundle::depends: A list of other resource bundles that this resource bundle depends on (detailed introduction in the next two sections).
  • yiiwebAssetBundle::jsOptions: When calling yiiwebView::registerJsFile() to register each JavaScript file in the bundle, specify the options passed to this method.
  • yiiwebAssetBundle::cssOptions: When calling yiiwebView::registerCssFile() to register each css file in the bundle, specify the options passed to this method.
  • yiiwebAssetBundle::publishOptions: When calling yiiwebAssetManager::publish() to publish the package resource file to the Web directory, specify the options passed to this method, only used when the yiiwebAssetBundle::sourcePath attribute is specified.

Resource location

Resources can be classified according to their location:

Source resources: Resource files and PHP source code are placed together and cannot be directly accessed by the Web. In order to use these source resources, they must be copied to a Web-accessible Web directory to become published resources. This process is called publishing. Resources will be introduced in detail later.
Publish resources: Resource files are placed in a Web directory that can be directly accessed through the Web;
External resources: Resource files are placed on a different web server than your web application;
When defining the resource bundle class, if you specify the yiiwebAssetBundle::sourcePath attribute, it means that any resources using relative paths will be used as source resources; if you do not specify this attribute, it means that these resources are published resources (therefore you should specify yiiwebAssetBundle ::basePath and yiiwebAssetBundle::baseUrl let Yii know their location).

It is recommended to place resource files in the web directory to avoid unnecessary resource publishing process. This is why the previous example specifies yiiwebAssetBundle::basePath instead of yiiwebAssetBundle::sourcePath.

For extensions, since their resources and source codes are in directories that cannot be accessed by the Web, the yiiwebAssetBundle::sourcePath attribute must be specified when defining the resource bundle class.

Note: Do not use @webroot/assets for the yiiwebAssetBundle::sourcePath attribute. This path defaults to the path where the yiiwebAssetManager resource manager stores the source resources after publishing them. All contents of this path will be considered temporary files and may be deleted. .
Resource Dependencies

When a web page contains multiple CSS or JavaScript files, they have a certain order to avoid property overwriting. For example, a web page must ensure that the jQuery JavaScript file has been included before using the jQuery UI widget. We call this The sequence of resources is called resource dependency.

Resource dependencies are mainly specified through the yiiwebAssetBundle::depends attribute. In the AppAsset example, the resource bundle depends on two other resource bundles: yiiwebYiiAsset and yiibootstrapBootstrapAsset. That is, the CSS and JavaScript files of the resource bundle must be in the two dependency bundles. Included after the file is included.

Resource dependencies are transitive, that is, if people say A depends on B and B depends on C, then A also depends on C.

Resource Options

可指定yii\web\AssetBundle::cssOptions 和 yii\web\AssetBundle::jsOptions 属性来自定义页面包含CSS和JavaScript文件的方式, 这些属性值会分别传递给 yii\web\View::registerCssFile() 和 yii\web\View::registerJsFile() 方法, 在视图 调用这些方法包含CSS和JavaScript文件时。

注意: 在资源包类中设置的选项会应用到该包中 每个 CSS/JavaScript 文件,如果想对每个文件使用不同的选项, 应创建不同的资源包并在每个包中使用一个选项集。
例如,只想IE9或更高的浏览器包含一个CSS文件,可以使用如下选项:

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

这会是包中的CSS文件使用以下HTML标签包含进来:

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

为链接标签包含

public $cssOptions = ['noscript' => true];
Copy after login

为使JavaScript文件包含在页面head区域(JavaScript文件默认包含在body的结束处)使用以下选项:

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

Bower 和 NPM 资源

大多数 JavaScript/CSS 包通过Bower 和/或 NPM管理, 如果你的应用或扩展使用这些包,推荐你遵循以下步骤来管理库中的资源:

修改应用或扩展的 composer.json 文件将包列入require 中, 应使用bower-asset/PackageName (Bower包) 或 npm-asset/PackageName (NPM包)来对应库。
创建一个资源包类并将你的应用或扩展要使用的JavaScript/CSS 文件列入到类中, 应设置 yii\web\AssetBundle::sourcePath 属性为@bower/PackageName 或 @npm/PackageName, 因为根据别名Composer会安装Bower或NPM包到对应的目录下。
注意: 一些包会将它们分布式文件放到一个子目录中,对于这种情况,应指定子目录作为 yii\web\AssetBundle::sourcePath属性值,例如,yii\web\JqueryAsset使用 @bower/jquery/dist 而不是 @bower/jquery。
使用资源包

为使用资源包,在视图中调用yii\web\AssetBundle::register()方法先注册资源, 例如,在视图模板可使用如下代码注册资源包:

use app\assets\AppAsset;
AppAsset::register($this); // $this 代表视图对象
Copy after login

如果在其他地方注册资源包,应提供视图对象,如在 小部件 类中注册资源包, 可以通过 $this->view 获取视图对象。

当在视图中注册一个资源包时,在背后Yii会注册它所依赖的资源包,如果资源包是放在Web不可访问的目录下,会被发布到可访问的目录, 后续当视图渲染页面时,会生成这些注册包包含的CSS和JavaScript文件对应的

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

See all articles