Home > Backend Development > PHP Tutorial > List the development advantages of PHP's Yii 2 framework, yii framework_PHP tutorial

List the development advantages of PHP's Yii 2 framework, yii framework_PHP tutorial

WBOY
Release: 2016-07-13 09:47:23
Original
760 people have browsed it

List the development advantages of Yii 2 framework for PHP, yii framework

We reported on the Yii framework when it was still in the RC (Release Candidate) stage, and at that time it Having just fully reached the release candidate stage, (and now that it's officially released) we feel it's time to revisit the topic: the reasons for choosing the Yii framework.

1. Easy to install

For web developers, time is money, and no one wants to spend their precious time on a complicated installation and configuration process.

Installation is handled using Composer. If you want to describe the installation process, Sitepoint recently published a great article here . I tend to use the basic application template, even if my website has a separate front-end and back-end components. Instead, I chose to use a module for the backend portion of my website. (Yii modules are best described as mini-applications that reside inside the main application).

Note: Many directory references are used in the following examples, starting from simple templates that use the directory structure.

2. Utilize modern technology

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

All class namespaces, which allows you to take advantage of PSR-4 compliant autoloaders. This means that including Yii's HTML helper classes is as simple as:

use yii\helpers\Html;
Copy after login

Yii also allows you to define aliases to help simplify your namespace. In the above example, the use statement will load a class definition, which is placed in the directory /vendor/yiisoft/yii2/helpers by default. This alias is defined in the BaseYii class on line 79:

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

The framework itself is installed using Composer, which is an extension. Even the process of publishing an extension is as easy as creating your own composer.json and hosting the code on Github, listing your extension on Packagist.

3. Highly scalable

Yii looks like a great-looking suit, but is also very easy to customize to your needs. Virtually every component of the framework is extensible. A simple example is to add a unique principal ID to your view. (If you are interested in why you might want to do this, you can read this article).

First, I will create a file named View.php in my appcomponents 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 . '"' : '';
  }
 
}
Copy after login

Then, in my main layout file (appviewslayoutsmain.php), I will add the following code inside the body tag of my HTML:

<body <&#63;=$this->BodyIdAttribute&#63;>>
Copy after login

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

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

4. Encourage testing

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

Codeception extension makes it easy to configure your application while testing. To test the application, simply 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',
    ],
  ],
];
Copy after login

When using the above configuration, you need to pay attention to the following matters:

  • During the functional acceptance test, all emails sent will be written to a file and saved instead of actually being sent.
  • The format of the URL during testing is index.php/controller/action, not /controller/action.
  • You need to use the test database instead of the production database when testing.

Codeception has a special module inside it, which is specially used for Yii framework testing. It adds some methods to the TestGuy class to ensure that Active Record (Yii's ORM) can work properly during functional testing. For example, if you want to see if the registration form successfully created a User object with the user name 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'));
Copy after login


5. Simplified security solution

Security is an important part of any web application, and luckily Yii has many great features to help ease the burden.

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

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

validatePassword: This is a method that can be used with generatePasswordHash and 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 会自动对所有非安全 HTTP 请求方法 (PUT, POST, DELETE) 的可用CSRF令牌进行检查, 并将在你使用 ActiveForm::begin() 方法创建你的开发表单标签时生成并输出一个令牌值. 这个特性可以通过编辑你的主配置文件,包含下面的代码来禁用:

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

为了堤防跨站脚本XSS的攻击,Yii提供了另外一个叫做 HtmlPurifier 的辅助类. 这个类有一个名为 process 的静态方法, 而它将会使用同名的 流行过滤器库 来过滤你的输出.

Yii 也包含了随时就绪的用于用户认证和授权的类. 授权被分成了两个类型: ACF (访问控制过滤器) 和RBAC (基于角色访问的控制).

两者中更加的是 ACF, 其实现是通过在你控制器的添加下列的 行为 方法:

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' => ['&#63;']
        ],
        [
          'allow' => true,
          'actions' => ['create'],
          'roles' => ['@']
        ]
      ]
    ];
  }
  // ...
}
Copy after login


上面的代码会告诉 DefaultControllerto 让访客用户访问login和view的action, 而不是create这个action. (问号 ? 是匿名用户的别名, 而 @ 表示的是已经被授权的用户).

RBAC 是一个可以在应用程序中指定那些用户可以执行特定的动作的强大方法. 它涉及为你的用户创建角色,为你的app定义权限,并然后为他们预期的角色使用这些角色. 如果你想要创建一个审核员(Moderator)的角色就可以使用这个方法, 并可以让所有分配到这个角色的用户可以对文章进行审核.

你也还可以使用 RBAC 定义规则, 它可以让你在特定条件下针对你应用程序的某些方面进行授权. 例如,你可以创建一个规则让用户可以编辑他们自己的文章, 而不能修改由其他人创建的文章.

6. 缩短开发时间

大多数的项目都包含了重复的任务,没有人想把时间浪费在这些重复工作上面。Yii 提供了一些工具来帮助你在这些任务上花费更少的时间,把大多数时间都用在定制应用来满足你客户的需求上。

其中最强大的一个工具就是“Gii”。Gii是一个基于web脚手架代码工具,它可以让你快速的创建一个代码模板如下所示:

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

Gii是高度可配置的。你可以设置它只从一个特定的环境加载。简单的编辑web配置文件如下:

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

这确保了Gii只有设置了Yii的环境变量为(development)开发环境时才加载,并且只在通过本地环境访问的时候加载。


现在,让我们来看看模型的生成:

201573142815193.jpg (1366×914)

表格名称使用了一个响应敲击就会显示的小窗口来尝试给出对你的模型将会关联的表格的猜测, 并且所有的域值输入框都会有一个翻转效果显示出来的提示,提醒你如何完成对它们的填写. 你可以在让Gii输出代码之前先进行一下预览, 而所有的代码模板都是完全可定制的.

也有几个可以用于数据库迁移、消息翻译(I18N)以及生成用于自动化测试数据库道具的命令行辅助工具. 例如,你可以使用如下代码创建一个新的数据库迁移 文件:

yii migrate/create create_user_table
Copy after login

这将会在 {应用目录}/migrations 创建一个新的看起来像下面这样的迁移模板:

<&#63;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;
    }
}
Copy after login

如此假如说我想要想这个表添加一些列. 我就只要简单的将下面的代码添加到 up 方法中:

public function up()
{
  $this->createTable('user', [
    'id' => Schema::TYPE_PK,
    'username' => Schema::TYPE_STRING . ' NOT NULL',
    'password_hash' => Schema:: TYPE_STRING . ' NOT NULL'
  ], null);
}
Copy after login

然后为了确保我可以进行迁移的逆向操作,我就会编辑down方法:

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

创建表格可能就是简单的设计到在命令行上运行一个命令:

./yii migrate
Copy after login

而删除表格是下面的这个命令:

./yii migrate/down
Copy after login

7. 很容易通过调整获得更好的性能

所有人都知道一个慢吞吞的网站会造就许多心怀不满的用户, 因此Yii为你提供了一些工具来帮助你让应用程序获得更快的速度.

所有的Yii缓存组件都扩展自yii/caching/Cache, 它能让你在使用一个公共API的同时选择任意某一个缓存系统. 你甚至可以同时注册多个高速缓存组件. Yii 当前支持数据库和文件系统缓存, 还有 APC, Memcache, Redis, WinCache, XCache 以及 Zend Data Cache.

默认情况下,如果你是使用的 Active Record ,那么 Yii 会额外运行一个查询来确定生成你模型的表的结构. 你可以通过像下面这样编辑你的主配置文件,对你的应用程序进行设置,以缓存这些表结构:

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


最后,Yii有一个命令行工具可以便于对前端字段进行缩小化. 简单地运行下面的命令就可以生成一个配置模板:

./yii asset/template config.php
Copy after login

然后编辑该配置,指定你想要用那些工具来执行缩小化操作(比如. Closure Compiler, YUI Compressor, 或者 UglifyJS). 生成的配置模板如下所示:

<&#63;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' => '',
    ],
  ];
Copy after login

接下来,运行这个控制台命令以执行压缩.

yii asset config.php /app/assets_compressed.php
Copy after login

最后,修改你的web应用程序配置文件,使用压缩后的资源.

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

注意: 你需要手动下载并安装这些额外的工具.

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1026547.htmlTechArticle列举PHP的Yii 2框架的开发优势,yii框架 当 Yii框架仍处于 RC(候选版)阶段时,我们 对它进行过报道,那时它刚刚全面达到候选版本阶段,...
Related labels:
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