Mastering Yii2: Harnessing the Power of Resource Bundles in Programming

WBOY
Release: 2023-08-31 15:49:08
Original
1238 people have browsed it

掌握 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.

Related Links

  • 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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template