Home > PHP Framework > YII > body text

Why should we choose yii framework

王林
Release: 2020-11-23 16:58:30
forward
4315 people have browsed it

Why should we choose yii framework

Background introduction:

SitePoint once published an article highlighting some of the top PHP frameworks. Yii (pronounced Yee) was tied for fourth at the time. Framework, the latest version is 1.1.14. Recently, Yii released version 2.0.

(Recommended tutorial: yii)

However, when we reported on it, it was still in RC status, and now the complete new version has just been released. I think it's time to reconsider the factors that go into choosing it.

Seven reasons to choose the yii framework:

1. Easy installation

For web developers, time is money. No one wants to waste their time on tedious installation and configuration.

Composer will handle the installation process. Well, if you want a description of the installation process, Sitepoint recently published an article about this, which you can read below. I prefer to stick with the basic app template even though I have a separate front-end and back-end component on my site. Instead, I chose to use a module for the backend portion of my site. (Yii modules are the best representation of mini-applications, used to embed into your main application.)

Note: The directory references in many of the examples below use the directory structure of a simple template.

2. Use modern technology

Yii is a pure OOP framework that makes full use of some of PHP's more advanced features, including delayed static binding, SPL classes and interfaces, and anonymous functions .

All classes are namespaced and allow you to take advantage of their PSR-4 compliant autoloader. In other words, including the HTML auxiliary classes in Yii, it is equally simple:

use yii\helpers\Html;
Copy after login

Yii can also define aliases to help simplify your namespace. In the above example, the use statement will load a class definition, and the default path in the directory is /vendor/yiisoft/yii2/helpers. 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, like its extensions. Publishing an extension is even as simple as creating a composer.json, hosting your code on Github, and listing the extension on Packagist. Yii can also define aliases to help simplify your namespace. In the above example, the use statement will load a class definition, and the default path in the directory is /vendor/yiisoft/yii2/helpers. This alias is defined in line 79 of the BaseYii class:

3. High scalability

Yii is like a suit, it looks big, but it is actually easy to adjust. Meet your needs. Virtually every component of the framework is extensible. A simple example is adding a unique body ID to your view. (If you want to know why you want to do this, you can check out this article)

First, I will create a file called View.php in my app\components and add the following content:

namespaceapp\components;
 
classView extendsyii\web\View {
 
    public$bodyId;
 
    /* Yii allows you to add magic getter methods by prefacing method names with "get" */
 
    publicfunction getBodyIdAttribute() {
        return($this->bodyId !='') ?'id="' . $this->bodyId .'"' : '';
    }
 
}
Copy after login

Then, in my main layout file (app\views\layouts\main.php), I want to add the following content in the body tag of the HTML:
BodyIdAttribute?>>

Finally, I want to add the following content to the main configuration file so that Yii can use the extended View class instead of the default one:

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

4, Encourage testing

Yii and Codeception are closely connected. Codeception is an amazing PHP testing framework that helps simplify the process of creating widgets, functional tests, and acceptance tests for your applications. Because every application you write is an automated test, right?

The Codeception extension will make configuring your application easier during testing. Simply provide the /tests/_config.php file to configure your test program. For example:

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

Using this configuration, the following situations will occur:

1. Any email sent during functional testing and acceptance testing will be written to a file in instead of being sent. Using this configuration, the following will happen:

2. The URLs in your tests will be in this format: index.php/controller/action instead of this: /controller/action

3. The test will use your test database, not your product database.

Exists in special modules in the Yii framework, and also exists in Codeception. It adds several methods to the TestGuy class to assist you in recording activities in functional testing (ORM in Yii). For example, if you want to see if a new user with the user name "testuser" was successfully created, you can do the following:

$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. Simplify security

Security Sex is an important part of any web application, and luckily, Yii has some great features to help you out in this area.
Yii comes with a secure application component, which exposes several methods to help create a more secure application. Some of the more useful methods are as follows:

·generatePasswordHash: Generate a secure one-way hash function from a password and random factors. This method compiles a random factor for you and then creates a one-way hash function from the string provided by PHP's crypt function.

·validatePassword:对于generatePasswordHash,这是一个伴侣功能,并且允许你检查用户提供的密码是否与你存储的散列函数相匹配。

·generateRandomKey:允许你创建一个任意长度的随机字符串。

Yii会对所有不安全的HTTP请求方法(PUT,POST,DELETE)进行自动检查,当你使用ActiveForm::begin()方法创建开放表单标签时,它会生成并输出一个token。通过编辑你的主配置文件可以禁止此功能,方法如下:

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

为了防止XSS,Yii提供了一个叫HtmlPurifier的辅助类。这个类有一个名为process的静态方法,并且会使用popular filter library过滤出同名的输出库。

Yii还包括备用类,用来进行用户身份验证和授权。授权分为两种类型:ACF(访问控制过滤器)和RBAC(基于角色的访问控制)。

这两种授权方法,较简单的要数ACF了,它是通过在你的控制器中添加以下行为方法来实现的:

useyii\filters\AccessControl;
 
classDefaultController extendsController {
    // ...
    publicfunction behaviors() {
        return[
            // ...
            'class'=> AccessControl::className(),
            'only'=> ['create','login','view'],
                'rules'=> [
                [
                    'allow'=> true,
                    'actions'=> ['login','view'],
                    'roles'=> ['?']
                ],
                [
                    'allow'=> true,
                    'actions'=> ['create'],
                    'roles'=> ['@']
                ]
            ]
        ];
    }
    // ...
}
Copy after login

上面的代码用于区分DefaultControllerto,允许guest用户的访问login 和view行为,而不是create 行为。(? 是一个匿名用户别名,@ 指的是已认证用户)。

RBAC是指那些用户可以在整个应用中执行特定操作行为的更有效的方法。包括为用户创建角色,定义app权限,然后使这些权限试用于相应的角色。如果你想创建一个Moderator的角色,并允许分配给该角色的所有用户批准文章。

你也可以使用RBAC定义角色,它允许你在特定条件下,授权访问应用的某些方面的自定义规则。例如,你可以创建一个规则,即允许用户编辑自己的文章,而不是那些其他人创建的。

6、缩短开发时间

大多数项目都会涉及一定的重复任务,没有人愿意浪费时间。而Yii提供的一些工具可以帮助你减少在这些任务中所花费的时间,将更多的时间用于定制让客户满意的应用。

在这些工具中,其中有一个名为“Gii”的工具最为强大。Gii是一个基于web的基架代码工具,可以让你快速创建代码模板:

  • ·模型

  • ·控制器

  • ·形式

  • ·模块

  • ·扩展

  • ·CRUD控制器行为和视图

Gii是高度可配置的。你可以将其设置为仅在特定的环境下加载。只需简单编辑下你的web配置文件即可,方法如下:

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

这样就可以确保党Yii的环境设置为开发的时候,Gii仅支持加载,并且它只通过本地主机访问时才会加载。

现在,让我们来看下模型生成器吧:

Why should we choose yii framework

表名使用的是一个预输入控件,来试图猜测哪个表格与你的模型相关联,并且所有领域都有一个翻转工具,提示你如何填写出来。在用Gii生成它之前,你可以预览代码,并且所有代码模板是完全可以自定义的。

还有几个命令行工具可以帮你为你的自动化测试创建数据库迁移,信息翻译(I18N:国际化)和数据库fixtures 代码模板。例如,你可以使用如下命令创建一个新的数据库迁移文件:

yii migrate/create create_user_table
Copy after login

这将会在 {appdir}/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;
        }
}
Copy after login

所以我们可以说,我想添加在该表中再添加几列。我只想添加以下内容到up 方法中:

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

然后,保证我可以反向迁移,下面我将添加down 方法:

public function down()
{
$this->dropTable(&#39;user&#39;);
}
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 数据缓存。

默认情况下,如果你正在使用Active Record,然后Yii会运行一个额外的查询,来确定表参与生成模型的架构。你可以通过编辑注配置文件设置应用程序,从而缓存这些架构:

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

最后,Yii有一个命令行工具,使前端资源极简化更容易。只需运行以下命令来生成配置模板:

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

然后,编辑该配置来指定工具,达到你想要的简化效果(如关闭编译器, YUI Compressor,或UglifyJS)。生成的配置模板,如下所示:

<?php
    return [
        &#39;jsCompressor&#39; => &#39;java -jar compiler.jar --js {from} --js_output_file {to}&#39;,
        &#39;cssCompressor&#39; => &#39;java -jar yuicompressor.jar --type css {from} -o {to}&#39;,
        &#39;bundles&#39; => [
            // &#39;yii\web\YiiAsset&#39;,
            // &#39;yii\web\JqueryAsset&#39;,
        ],
        &#39;targets&#39; => [
            &#39;app\config\AllAsset&#39; => [
                &#39;basePath&#39; => &#39;path/to/web&#39;,
                &#39;baseUrl&#39; => &#39;&#39;,
                &#39;js&#39; => &#39;js/all-{hash}.js&#39;,
                &#39;css&#39; => &#39;css/all-{hash}.css&#39;,
            ],
        ],
        &#39;assetManager&#39; => [
            &#39;basePath&#39; => __DIR__,
            &#39;baseUrl&#39; => &#39;&#39;,
        ],
    ];
Copy after login

接着,运行此控制台命令来实现压缩:

&#39;components&#39; => [
    // ...
    &#39;assetManager&#39; => [
        &#39;bundles&#39; => require &#39;/app/assets_compressed.php&#39;
    ]
]
Copy after login

注意:你必须要手动下载和安装这些外部工具。

结论:

像任何一个好的框架一样,Yii能够帮助你快速创建流行的web应用,并确保它们可以做的很好。通过做许多繁琐的事情,它帮你你创建安全的和可测试的网站。你可以轻松的使用它提供的大部分功能,或者你也可以修改其中任何一个来适应你的需求。真心建议你在你的下一个web项目中考虑一下它!

The above is the detailed content of Why should we choose yii framework. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!