Enumerating the development advantages of the Yii 2 framework of PHP, YII framework _php Tutorial

Source: Internet
Author: User

Enumerating the development advantages of the Yii 2 framework of PHP, the YII framework


When the YII framework is still in the RC (candidate) phase, we have reported it, when it has just reached its full candidate version stage, (now it has released the official version) we feel it's time to revisit this topic: the reason for choosing the YII framework.

1. Easy to install

For web developers, time is money, and no one wants to spend valuable time in a complex setup and configuration process.

Installation processing uses composer. If you want to describe the installation process, sitepoint recently published a great article here. I tend to use basic application templates even though my site has a separate front-end and back-end component. Instead, I chose to use a module to give the background part of my site. (Yii modules are the best description, and small applications reside in the main application).

Note: Many of the directories are referenced in the following example, from a simple template to the structure of the directory used.

2. Use of modern technology

Yii is a purely object-oriented framework and takes advantage of some of the more advanced features of PHP, including lazy static bindings, SPL classes and interfaces, and anonymous functions.

All class namespaces, which allow you to take advantage of PSR-4 compatible auto loaders. This means that the Help class of the HTML that includes Yii is as simple as:

Use yii\helpers\html;

Yii also allows you to define aliases to help simplify your namespace. In the example above, the USE statement loads a class definition, which is placed by default in the directory/vendor/yiisoft/yii2/helpers. This alias is defined in line 79th of the Baseyii class:

public static $aliases = [' @yii ' = = __dir__];

The installation of the framework itself uses composer, which is its extension. Even publishing the process extension is as easy as creating your own Composer.json, and in GitHub managed code, list your extensions in Packagist.

3. High degree of scalability

Yii looks like a great suit, but it's also very easy to customize according to your needs. Virtually every component of the framework can be extended. A simple example is to add a unique principal ID to your view. (If you're interested in why you might want to do this, take a look at this article).

First, I'll create a file named view.php in my app\components directory face reading, and add the following code:

namespace App\components; Class View extends Yii\web\view {public   $bodyId;   /* YII allows you to add magic getter methods by prefacing method names with "get" */public   function Getbodyidattribu Te () {    return ($this->bodyid! = ")? ' Id= '. $this->bodyid. '"' : '';  } }

Then, in my main layout file (app\views\layouts\main.php), I'll add the following code to the inside of my body tag in my HTML:

<?="$this-">Bodyidattribute?>>

And finally, I'll add the following code to my main profile to let Yii know how to use my extended view class instead of its own default class:

return [  //...  ] Components ' = + [    //...    ' View ' = ' [      ' class ' = ' App\components\view ']]    ;

4. Encourage testing

The YII framework and the codeception framework are tightly integrated. Codeception is an excellent PHP testing framework that helps streamline the process of creating unit tests and functional acceptance tests. The condition is that you're writing automated test cases for all of your applications, right?

The codeception extension makes it easy to configure your application at test time. To test the application, just edit an existing file/tests/_config.php. For example:

return [  ' components ' + = [' mail ' = ' = ' usefiletransport ' = ' + '    ,],    ' urlmanager ' = > [      ' showscriptname ' = True,    ],    ' db ' = = [        ' dsn ' = ' mysql:host=localhost;dbname= Mysqldb_test ',    ],  ],];

With the above configuration, there are a few things to note:

    • During the feature acceptance test, all sent messages are saved in a file, not really sent.
    • The format of the URL when testing is index.php/controller/action, not/controller/action.
    • Testing requires the use of a test database, not a production database.

There is a special module inside the codeception that is specifically designed for YII framework testing. It adds some methods to the Testguy class to ensure that the Active Record (Yii ORM) works properly when the function is tested. For example, if you want to see if the registration form has successfully created a user object named TestUser, you can do this:

$I->amonpage (' register '), $I->fillfield (' username ', ' testuser '), $I->fillfield (' Password ', ' qwerty '); $I- >click (' Register '); $I->seerecord (' App\models\user ', Array (' name ' = ' testuser '));


5. Simplified Security Solutions

Security is an important part of any Web application, and fortunately Yii has a number of great features that can help you reduce your burden.

Yii brings a security application component that exposes a number of methods that can help you to create a more secure application. Some of the relatively more useful methods are:

Generatepasswordhash: Generates a secure hash value from a password and a random salt value. This method creates a random salt value for you, and then uses PHP's crypt function to create a hash value based on the supplied string.

ValidatePassword: This is a method that can be used with Generatepasswordhash and allows you to check that the user-supplied password matches the hash you stored.

Generaterandomkey: Reversible lets you create a random string of any length

Yii automatically checks the available CSRF tokens for all non-secure HTTP request Methods (PUT, POST, DELETE) and generates and outputs a token value when you create your development form label using the Activeform::begin () method. This feature can be disabled by editing your master configuration file, which contains the following code:

  return [' components ' + = ['      request ' = [        ' enablecsrfvalidation ' and ' = False,      ]  ];

In order to attack the cross-site scripting XSS, Yii provides another helper class called Htmlpurifier. This class has a static method called process, and it will filter your output using a popular filter library of the same name.

Yii also includes a ready-to-use class for user authentication and authorization. Authorization is divided into two types: ACF (access control filter) and RBAC (role-based access control).

The more the two are ACF, its implementation is done by adding the following behavior method in your controller:

Use Yii\filters\accesscontrol; Class Defaultcontroller extends Controller {  //...  Public Function Behaviors () {    return [      //...]      Class ' = ' + Accesscontrol::classname (),      ' only ' + = [' Create ', ' login ', ' view '],        ' rules ' and ' = [          ' Allow ' = ' and          ' actions ' = [' login ', ' view '],          ' roles ' = ['? ']        ],        [          ' Allow ' = True,          ' actions ' = [' Create '],          ' roles ' = [' @ ']]]    ;  }  // ...}


The code above tells Defaultcontrollerto to let the guest user access the login and view action instead of the create action. (question mark? is the alias of the anonymous user, and @ represents the user who is already authorized).

RBAC is a powerful way to specify which users can perform specific actions in an application. It involves creating roles for your users, defining permissions for your app, and then using those roles for the roles they expect. You can use this method if you want to create a role as an auditor (moderator), and you can have all users assigned to the role review the article.

You can also use RBAC to define rules that allow you to authorize certain aspects of your application under certain conditions. For example, you can create a rule that allows users to edit their own articles without modifying an article created by someone else.

6. Shorten development time

Most projects contain repetitive tasks, and no one wants to waste their time on the repetitive work. YII provides tools to help you spend less time on these tasks, and most of the time in custom applications to meet the needs of your customers.

One of the most powerful tools is the "Gii". The GII is a Web-based scaffolding code tool that allows you to quickly create a code template as follows:

    • Models
    • Controllers
    • Forms
    • Modules
    • Extensions
    • CRUD Controller actions and views

The GII is highly configurable. You can set it to load only from a specific environment. The simple edit Web configuration file is as follows:

if (Yii_env_dev) {  //...  $config [' Modules '] [' gii '] = [    ' class ' = ' Yii\gii\module ', ' allowedips ' = ' = '    127.0.0.1 ', ':: 1 ']  }

This ensures that the GII is only loaded when the environment variable for the (development) development environment is set, and only when accessed through the local environment.


Now, let's look at the model generation:

The table name uses a small window that responds to a hit and tries to give a guess of the table that your model will be associated with, and all of the field value input boxes will have a flip effect to show you how to complete them. You can preview the GII before you export the code, and all of the code templates are fully customizable.

There are also several command-line aids that can be used for database migration, message translation (i18n), and for generating props for automated test database. For example, you can create a new database migration file with the following code:

Yii migrate/create create_user_table

This will create a new migration template that looks like this in the {app directory}/migrations:

<?php use   Yii\db\schema;   Class M140924_153425_create_user_table extends \yii\db\migration  {public    function up ()    {     }     Public function down ()    {      echo ' m140924_153425_create_user_table cannot be reverted.\n ';       return false;    }}

So if I want to think about this table, add some columns. I just simply add the following code to the UP method:

Public function up () {  $this->createtable (' user ', [    ' id '] = schema::type_pk,    ' username ' = Schema::type_string. ' Not NULL ',    ' password_hash ' = ' Schema:: type_string. ' NOT NULL '  ], null);}

Then to make sure I can do the reverse of the migration, I'll edit the down method:

Public function down () {  $this->droptable (' user ');}

Creating a table might be a simple design to run a command on the command line:

./yii Migrate

And the Delete table is the following command:

./yii Migrate/down

7. Easy to adjust for better performance

Everyone knows that a slow website can create a lot of disgruntled users, so Yii provides you with tools to help you get your application to speed faster.

All Yii cache components are extended from Yii/caching/cache, which allows you to select any one of the cache systems while using a common API. You can even register multiple cache components at the same time. YII currently supports database and file system caches, as well as APC, Memcache, Redis, Wincache, XCache, and Zend Data caches.

By default, if you are using an Active Record, Yii will run an extra query to determine the structure of the table that generated your model. You can set up your application to cache these table structures by editing your master configuration file as follows:

return [  //...  ] Components ' = + [    //...    ' db ' = = [      //...      ' Enableschemacache ' + True,      ' schemacacheduration ' = 3600,      ' schemacache ' = ' cache ', ',    ' Cache ' = ' [      ' class ' = ' Yii\caching\filecache ',],]  ,;


Finally, Yii has a command-line tool that facilitates the reduction of front-end fields. Simply run the following command to generate a configuration template:

./yii Asset/template config.php

Then edit the configuration to specify the tools you want to use to perform the zoom out (for example. Closure Compiler, YUI Compressor, or UGLIFYJS). The resulting configuration template is as follows:

<?php  return [    ' jscompressor ' = ' Java-jar Compiler.jar--js {from}--js_output_file {to} ',    ' Csscompressor ' + ' Java-jar Yuicompressor.jar--type css {from}-o {to} ',    ' bundles ' = = [      //' Yii\web\yiiass Et ',      //' Yii\web\jqueryasset ',    ],    ' targets ' = = [      ' app\config\allasset '        = ' = ' basepath ' = > ' Path/to/web ',        ' baseUrl ' + = ',        ' js ' = ' js/all-{hash}.js ',        ' css ' = ' css/all-{hash '. CSS ',      ],    ],    ' assetmanager ' = [      ' basepath ' = ' __dir__,      ' baseUrl ' =    ', ', '  ];

Next, run this console command to perform the compression.

Yii Asset config.php/app/assets_compressed.php

Finally, modify your Web application configuration file to use the compressed resource.

' Components ' = [  //...  ' Assetmanager ' = = [    ' bundles ' = ' + require '/app/assets_compressed.php '  ]

Note: You need to manually download and install these additional tools.

http://www.bkjia.com/PHPjc/1026547.html www.bkjia.com true http://www.bkjia.com/PHPjc/1026547.html techarticle enumerating the development advantages of the Yii 2 framework of PHP, the YII framework when the YII framework is still in the RC (candidate) phase, we have reported it, when it has just fully reached the candidate version stage, ...

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