List the development advantages of PHP's Yii2 framework

Source: Internet
Author: User
This article mainly introduces the development advantages of PHP's Yii2 framework. it is precisely because of the emergence of many emerging frameworks that PHP's vitality can be maintained, when the Yii Framework is still in the RC (Candidate Version) stage, we have reported it. at that time, it was just reaching the Candidate Version stage, (Now it has released the official version.) we feel it is time to discuss this topic again: the reason for choosing the Yii Framework.

1. easy to install

For web developers, time is money, and no one is willing to spend valuable time in a complicated installation and configuration process.

Use Composer for installation. If you want to describe the installation process, Sitepoint recently published a great article here. I tend to use basic application templates, even if my website has a separate front-end and back-end component. Instead, I chose to use a module for the background part of my website. (The Yii module is the best description. small applications reside in the main application ).

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

2. use modern technology

Yii is a pure object-oriented framework that leverages some of PHP's more advanced features, including delayed static binding, SPL classes and interfaces, and anonymous functions.

All class namespaces that allow you to take advantage of PSR-4-compatible automatic loaders. This means that the help class of HTML including Yii is as simple:

use yii\helpers\Html;

Yii also allows you to define aliases to help simplify your namespace. In the preceding example, the use statement loads a class definition. the default directory is/vendor/yiisoft/yii2/helpers. this alias is defined in BaseYii class in row 79th:

public static $aliases = ['@yii' => __DIR__];

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

3. high scalability

Yii looks like a great suit, but it is very easy to customize according to your needs. In fact, every component of the framework can be expanded. A simple example is to add a unique subject ID to your view. (If you are interested in why you might want to do so, read this article ).

First, I will create a file named View. php in the photo of my app \ components directory 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 getBodyIdAttribute() {    return ($this->bodyId != '') ? 'id="' . $this->bodyId . '"' : '';  } }

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

BodyIdAttribute?>>

In the end, I will add the following code to my main configuration file to let Yii know how to use the expanded view class instead of its own default class:

return [  // ...  'components' => [    // ...    'view' => [      'class' => 'app\components\View'    ]    ]];

4. Encourage Testing

The Yii Framework and Codeception framework are closely integrated. Codeception is an excellent PHP testing framework that helps simplify the process of creating unit tests and functional acceptance tests. The condition is that you are writing automated test cases for all applications, right?

The Codeception extension simplifies application configuration during testing. To test the application, you only need to edit an existing file/tests/_ config. php. For example:

return [  'components' => [    'mail' => [      'useFileTransport' => true,    ],    'urlManager' => [      'showScriptName' => true,    ],    'db' => [        'dsn' => 'mysql:host=localhost;dbname=mysqldb_test',    ],  ],];

Note the following when using the above configuration:

  • During the function acceptance test, all emails sent will be written to a file for storage, rather than being actually sent out.
  • During the test, the URL format is index. php/controller/action, rather than/controller/action.
  • You must use the test database instead of the production database for testing.

Codeception has a special module dedicated for Yii Framework testing. It adds some methods to the TestGuy class to ensure that the Active Record (Yii ORM) works normally during function testing. For example, if you want to check whether the registry list 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. Fortunately, Yii has many great features that can help ease the burden.

Yii provides a security application component that exposes some methods that can be used to create a safer application. some of the more useful methods are:

GeneratePasswordHash: generate a secure hash value from a password and a random salt value. this method will create a random salt value for you, and then use the crypt function of PHP to create a hash value based on the provided string.

ValidatePassword: This method can be used in combination with generatePasswordHash. It also allows you to check whether the password provided by the user matches the hash value you store.

GenerateRandomKey: reversible allows you to create a random string of any length

Yii will automatically check the available CSRF tokens for all insecure HTTP request methods (PUT, POST, DELETE), and will use ActiveForm: begin () method to generate and output a token value when creating your development form tag. this feature can be disabled by editing your main configuration file, including the following code:

  return [    'components' => [      'request' => [        'enableCsrfValidation' => false,      ]  ];

Yii provides an auxiliary class called HtmlPurifier for cross-site scripting XSS attacks. this class has a static method named process, and it will use a popular filter library with the same name to filter your output.

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

The two are more ACF, which is implemented by adding the following behavior methods to your controller:

use yii\filters\AccessControl; class DefaultController extends Controller {  // ...  public function behaviors() {    return [      // ...      'class' => AccessControl::className(),      'only' => ['create', 'login', 'view'],        'rules' => [        [          'allow' => true,          'actions' => ['login', 'view'],          'roles' => ['?']        ],        [          'allow' => true,          'actions' => ['create'],          'roles' => ['@']        ]      ]    ];  }  // ...}


The above code will tell defacontrocontrollerto allow guest users to access the action of login and view, rather than create this action. (question mark? Is the alias of an anonymous user, while @ indicates an authorized user ).

RBAC is a powerful method that allows users to execute specific actions in an application. it involves creating roles for your users, defining permissions for your apps, and then using these roles for their expected roles. if you want to create a Moderator role, you can use this method and allow all users assigned to this role to review the article.

You can also use RBAC to define rules that allow you to authorize certain aspects of your application under specific conditions. for example, you can create a rule so that users can edit their own articles, rather than modifying the articles created by others.

6. shorten development time

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

One of the most powerful tools is Gii ". 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

Gii is highly configurable. You can set it to load only from a specific environment. Edit the web configuration file as follows:

 if (YII_ENV_DEV) {  // ...  $config['modules']['gii'] = [    'class' => 'yii\gii\Module',    'allowedIPs' => ['127.0.0.1', '::1']  ]}

This ensures that Gii is loaded only when the environment variable of Yii is set to the development environment and only when accessed through the local environment.


Now let's take a look at the generation of the model:

The table name uses a small window that will be displayed when a response is struck to give a guess about the table associated with your model, in addition, all the field value input boxes will display a tip indicating how to fill them out. you can preview the code before making Gii output, and all the code templates are completely customizable.

There are also several command line auxiliary tools that can be used for database migration, Message Translation (I18N), and generation for automated test database props. for example, you can use the following code to create a new database migration file:

yii migrate/create create_user_table

This will create a new migration template that looks like the following in {application 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 add some columns to this table, I just need to 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 ensure that I can perform reverse migration operations, I will edit the down method:

public function down(){  $this->dropTable('user');}

Creating a table may be simply designed to run a command on the command line:

./yii migrate

The following command is used to delete a table:

./yii migrate/down

7. it is easy to achieve better performance through adjustment

Everyone knows that a slow website will create many unhappy users. Therefore, Yii provides you with some tools to help you make your applications faster.

All Yii Cache components are extended from yii/caching/Cache, which allows you to select any Cache system while using a public API. you can even register multiple cache components at the same time. yii currently supports database and file system Cache, including APC, Memcache, Redis, WinCache, XCache, and Zend Data Cache.

By default, if you are using Active Record, Yii will run an additional query to determine the structure of the table that generates your model. you can edit your primary configuration file as follows and set your application to cache these table structures:

return [  // ...  'components' => [    // ...    'db' => [      // ...      'enableSchemaCache' => true,      'schemaCacheDuration' => 3600,      'schemaCache' => 'cache',    ],    'cache' => [      'class' => 'yii\caching\FileCache',    ],  ],];


Finally, Yii has a command line tool to scale down 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 scaling operations (such as. Closure Compiler, YUI Compressor, or UglifyJS). The generated 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\YiiAsset',      // '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 the console command to perform compression.

yii asset config.php /app/assets_compressed.php

Finally, modify your web application configuration file and use the compressed resources.

'components' => [  // ...  'assetManager' => [    'bundles' => require '/app/assets_compressed.php'  ]]

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

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.