Table of Contents
What is an asset package?
Build asset package
Create resource package
Load resource package
What’s next?
Related Links
Home Web Front-end HTML Tutorial Mastering Yii2: Harnessing the Power of Resource Bundles in Programming

Mastering Yii2: Harnessing the Power of Resource Bundles in Programming

Aug 31, 2023 pm 03:49 PM

掌握 Yii2:在编程中利用资源包的力量

If you're asking "What is Yii?" check out my previous tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and provides an overview of the 2014-10 New features of Yii 2.0 released in March. Well>

In this Yii2 programming series, I will guide readers in using the newly upgraded Yii2 PHP framework. In this tutorial, I'll show you how to add custom JavaScript and CSS scripts and libraries to your Yii application. Yii uses a concept called Asset Bundles to make it easier to manage these resources.

For these examples we will continue to build on the simple state application from the previous tutorial.

As a reminder, I do participate in the comment thread below. I'd be particularly interested if you have a different approach, additional ideas, or would like to suggest topics for future tutorials.

What is an asset package?

Yii's resource bundles represent groups of JavaScript and CSS files that need to be included together on a specific page or an entire website. Resource bundles make it easy to group together specific scripts and styles for specific areas of your site. For example, in my Meeting Planner application, I can easily include the Google Places API on only the pages I need.

This is a simple example. We create a \frontend\assets\LocateAsset.php file:

<?php

namespace frontend\assets;

use yii\web\AssetBundle;

class LocateAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
    ];
    public $js = [
      'js/locate.js',
      'js/geoPosition.js',
      'https://maps.google.com/maps/api/js?sensor=false',
    ];
    public $depends = [
    ];
}
Copy after login

Then we load it into our view file - it's really simple:

<?php

use yii\helpers\Html;
use yii\helpers\BaseHtml;
use yii\widgets\ActiveForm;

use frontend\assets\LocateAsset;
LocateAsset::register($this);

...
Copy after login

When you view the source code of our pages, you will see the generated scripts as well as other Yii2 standard resources for forms, Bootstrap, etc.:

<script src="/mp/js/locate.js"></script>
<script src="/mp/js/geoPosition.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="/mp/assets/d9b337d3/jquery.js"></script>
<script src="/mp/assets/ed797b77/yii.js"></script>
<script src="/mp/assets/ed797b77/yii.validation.js"></script>
<script src="/mp/assets/ed797b77/yii.activeForm.js"></script>
<script src="/mp/assets/8c5c0263/js/bootstrap.js"></script>
Copy after login

In this tutorial, I'll guide you through using a resource bundle to integrate character counting into our status form. We'll use this to enforce a character limit, similar to Twitter's 140 character maximum.

If you are interested in seeing this feature in Yii1.x, I implemented it in Building with the Twitter API: OAuth, Read and Post (Tuts).

Build asset package

Create resource package

In the \assets directory, we create StatusAsset.php:

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class StatusAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [];
    public $js = [
      '/js/jquery.simplyCountable.js',
      '/js/twitter-text.js',
      '/js/twitter_count.js',  
      '/js/status-counter.js',
    ];
    public $depends = [
            'yii\web\YiiAsset',
            'yii\bootstrap\BootstrapAsset',
        ];
}
Copy after login

I used a combination of the jQuery simpleCountable plugin, twitter-text.js (Twitter's text processing script based on JavaScript), and the script responsible for URL shaping: twitter_count.js; in Twitter, URLs are counted as 20 characters. These files are in \web\js.

I also created a document ready function to call them in \web\js\status-counter.js. Including yii\web\YiiAsset in our $depends array will ensure that JQuery is loaded whenever we instantiate this resource.

$(document).ready(function()
{
  $('#status-message').simplyCountable({
    counter: '#counter2',
    maxCount: 140,
    countDirection: 'down'
  });
});
Copy after login

Load resource package

Instantiating a resource package is very simple, as shown in the following \views\status\_form.:

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

use app\assets\StatusAsset;
StatusAsset::register($this);

/* @var $this yii\web\View */
/* @var $model app\models\Status */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="status-form">
    <?php $form = ActiveForm::begin(); ?>
    
    <div class="row">
      <div class="col-md-8">
      <?= $form->field($model, 'message')->textarea(['rows' => 6]) ?>
      </div>
      <div class="col-md-4">
      <p>Remaining: <span id="counter2">0</span></p>
      </div>
    </div>
Copy after login

That’s all you need to activate our Twitter-style character counter:

掌握 Yii2:在编程中利用资源包的力量

I find Yii Asset Bundles simple and easy to manage. They help me reuse parts of JavaScript and CSS in certain areas of the application in an organized way.

What’s next?

The Yii2 Definitive Guide describes many of the advanced features of Asset Bundles. You can control where the scripts are loaded for each package, e.g. POS_HEAD, POS_END. You can set up asset mappings to load specific compatible versions of libraries. You can set JavaScript and CSS options to further conditionally load bundles. You can also use resource converters to compile LESS code to CSS or TypeScript to JavaScript.

Check out the upcoming tutorials in my "Programming with Yii2" series as we continue to dive into different aspects of the framework. You may also want to check out my "Building Your Startup with PHP" series, which uses advanced templates for Yii2 as I build real-world applications.

I welcome feature and theme requests. You can post them in the comments below or send me an email on my Lookahead Consulting website.

If you would like to know when the next Yii2 tutorial is released, follow me on Twitter @reifman or check out my instructor page. My instructor page will immediately contain all articles from this series.

  • The Definitive Guide to Yii2: Assets
  • Yii2 AssetBundle class documentation
  • Yii2 Developer Exchange, the author's Yii2 resource site

The above is the detailed content of Mastering Yii2: Harnessing the Power of Resource Bundles in Programming. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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)

Hot Topics

Java Tutorial
1660
14
PHP Tutorial
1260
29
C# Tutorial
1233
24
Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

HTML, CSS, and JavaScript: Essential Tools for Web Developers HTML, CSS, and JavaScript: Essential Tools for Web Developers Apr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

HTML: The Structure, CSS: The Style, JavaScript: The Behavior HTML: The Structure, CSS: The Style, JavaScript: The Behavior Apr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web Design The Future of HTML: Evolution and Trends in Web Design Apr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

The Future of HTML, CSS, and JavaScript: Web Development Trends The Future of HTML, CSS, and JavaScript: Web Development Trends Apr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

See all articles