Home >Backend Development >PHP Tutorial >7 Reasons to Choose Yii 2 Framework_PHP Tutorial

7 Reasons to Choose Yii 2 Framework_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:13:421267browse

7 Reasons to Choose Yii 2 Framework

Last year, the SitePoint website published an article highlighting some of the top PHP development frameworks. Ranked fourth is the Yii (pronounced the same as Yee) framework. At that time, the latest version of Yii framework was 1.1.14. Recently, Yii version 2.0 was released, and you can use version 2.0 in your product.

We reported on the Yii framework when it was still in the RC candidate stage, when it had just fully reached the release candidate stage, and now that it has released an official version we feel it is time to discuss this topic again: Choice The reason for 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:

<ol class="dp-c"><li class="alt"><span><span class="keyword">use</span><span> yii\helpers\Html; </span></span></li></ol>

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:


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:

<ol class="dp-c"><li class="alt"><span><span>namespace app\components; </span></span></li><li><span>  </span></li><li class="alt"><span><span class="keyword">class</span><span> View </span><span class="keyword">extends</span><span> yii\web\View { </span></span></li><li><span>  </span></li><li class="alt"><span>    <span class="keyword">public</span><span> </span><span class="vars">$bodyId</span><span>; </span></span></li><li><span>  </span></li><li class="alt"><span>    <span class="comment">/* Yii allows you to add magic getter methods by prefacing method names with "get" */</span><span> </span></span></li><li><span>  </span></li><li class="alt"><span>    <span class="keyword">public</span><span> </span><span class="keyword">function</span><span> getBodyIdAttribute() { </span></span></li><li><span>        <span class="keyword">return</span><span> (</span><span class="vars">$this</span><span>->bodyId != </span><span class="string">''</span><span>) ? </span><span class="string">'id="'</span><span> . </span><span class="vars">$this</span><span>->bodyId . </span><span class="string">'"'</span><span> : </span><span class="string">''</span><span>; </span></span></li><li class="alt"><span>    } </span></li><li><span>  </span></li><li class="alt"><span>} </span></li></ol>

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

<ol class="dp-c"><li class="alt"><span><span><body <?=</span><span class="vars">$this</span><span>->BodyIdAttribute?>> </span></span></li></ol>

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:

<ol class="dp-c"><li class="alt"><span><span class="keyword">return</span><span> [ </span></span></li><li><span>    <span class="comment">// ...</span><span> </span></span></li><li class="alt"><span>    <span class="string">'components'</span><span> => [ </span></span></li><li><span>        <span class="comment">// ...</span><span> </span></span></li><li class="alt"><span>        <span class="string">'view'</span><span> => [ </span></span></li><li><span>            <span class="string">'class'</span><span> => </span><span class="string">'app\components\View'</span><span> </span></span></li><li class="alt"><span>        ]    </span></li><li><span>    ] </span></li><li class="alt"><span>]; </span></li></ol>

4. Encourage testing

The

Yii framework and the Codeceptionframework 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:

<ol class="dp-c"><li class="alt"><span><span class="keyword">return</span><span> [ </span></span></li><li><span>    <span class="string">'components'</span><span> => [ </span></span></li><li class="alt"><span>        <span class="string">'mail'</span><span> => [ </span></span></li><li><span>            <span class="string">'useFileTransport'</span><span> => true, </span></span></li><li class="alt"><span>        ], </span></li><li><span>        <span class="string">'urlManager'</span><span> => [ </span></span></li><li class="alt"><span>            <span class="string">'showScriptName'</span><span> => true, </span></span></li><li><span>        ], </span></li><li class="alt"><span>        <span class="string">'db'</span><span> => [ </span></span></li><li><span>                <span class="string">'dsn'</span><span> => </span><span class="string">'mysql:host=localhost;dbname=mysqldb_test'</span><span>, </span></span></li><li class="alt"><span>        ], </span></li><li><span>    ], </span></li><li class="alt"><span>]; </span></li></ol>

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

There is a special module inside Codeception, specifically used for Yii framework testing. It adds some methods to the TestGuy class to ensure that Active RecordYii'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:

<ol class="dp-c"><li class="alt"><span><span class="vars">$I</span><span>->amOnPage(</span><span class="string">'register'</span><span>); </span></span></li><li><span><span class="vars">$I</span><span>->fillField(</span><span class="string">'username'</span><span>, </span><span class="string">'testuser'</span><span>); </span></span></li><li class="alt"><span><span class="vars">$I</span><span>->fillField(</span><span class="string">'password'</span><span>, </span><span class="string">'qwerty'</span><span>); </span></span></li><li><span><span class="vars">$I</span><span>->click(</span><span class="string">'Register'</span><span>); </span></span></li><li class="alt"><span><span class="vars">$I</span><span>->seeRecord(</span><span class="string">'app\models\User'</span><span>, </span><span class="keyword">array</span><span>(</span><span class="string">'name'</span><span> => </span><span class="string">'testuser'</span><span>)); </span></span></li></ol>

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 comes with a Security application component, which exposes some methods that can help create a more secure application. Some of the more useful methods are:

  • generatePasswordHash: Generate 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 in conjunction with generatePasswordHash, and allows you to check whether the password provided by the user matches the hash value you store.

  • generateRandomKey: 可逆让你创建一个任何长度的随机字符串

Yii 会自动对所有非安全 HTTP 请求方法 (PUT, POST, DELETE) 的可用CSRF令牌进行检查, 并将在你使用 ActiveForm::begin() 方法创建你的开发表单标签时生成并输出一个令牌值. 这个特性可以通过编辑你的主配置文件,包含下面的代码来禁用:

<ol class="dp-c"><li class="alt"><span><span class="keyword">return</span><span> [ </span></span></li><li><span>    <span class="string">'components'</span><span> => [ </span></span></li><li class="alt"><span>        <span class="string">'request'</span><span> => [ </span></span></li><li><span>            <span class="string">'enableCsrfValidation'</span><span> => false, </span></span></li><li class="alt"><span>        ] </span></li><li><span>]; </span></li></ol>

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

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

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

<ol class="dp-c"><li class="alt"><span><span class="keyword">use</span><span> yii\filters\AccessControl; </span></span></li><li><span>  </span></li><li class="alt"><span><span class="keyword">class</span><span> DefaultController </span><span class="keyword">extends</span><span> Controller { </span></span></li><li><span>    <span class="comment">// ...</span><span> </span></span></li><li class="alt"><span>    <span class="keyword">public</span><span> </span><span class="keyword">function</span><span> behaviors() { </span></span></li><li><span>        <span class="keyword">return</span><span> [ </span></span></li><li class="alt"><span>            <span class="comment">// ...</span><span> </span></span></li><li><span>            <span class="string">'class'</span><span> => AccessControl::className(), </span></span></li><li class="alt"><span>            <span class="string">'only'</span><span> => [</span><span class="string">'create'</span><span>, </span><span class="string">'login'</span><span>, </span><span class="string">'view'</span><span>], </span></span></li><li><span>                <span class="string">'rules'</span><span> => [ </span></span></li><li class="alt"><span>                [ </span></li><li><span>                    <span class="string">'allow'</span><span> => true, </span></span></li><li class="alt"><span>                    <span class="string">'actions'</span><span> => [</span><span class="string">'login'</span><span>, </span><span class="string">'view'</span><span>], </span></span></li><li><span>                    <span class="string">'roles'</span><span> => [</span><span class="string">'?'</span><span>] </span></span></li><li class="alt"><span>                ], </span></li><li><span>                [ </span></li><li class="alt"><span>                    <span class="string">'allow'</span><span> => true, </span></span></li><li><span>                    <span class="string">'actions'</span><span> => [</span><span class="string">'create'</span><span>], </span></span></li><li class="alt"><span>                    <span class="string">'roles'</span><span> => [</span><span class="string">'@'</span><span>] </span></span></li><li><span>                ] </span></li><li class="alt"><span>            ] </span></li><li><span>        ]; </span></li><li class="alt"><span>    } </span></li><li><span>    <span class="comment">// ...</span><span> </span></span></li><li class="alt"><span>} </span></li></ol>

上面的代码会告诉 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配置文件如下:

<ol class="dp-c"><li class="alt"><span><span class="keyword">if</span><span> (YII_ENV_DEV) { </span></span></li><li><span>    <span class="comment">// ...</span><span> </span></span></li><li class="alt"><span>    <span class="vars">$config</span><span>[</span><span class="string">'modules'</span><span>][</span><span class="string">'gii'</span><span>] = [ </span></span></li><li><span>        <span class="string">'class'</span><span> => </span><span class="string">'yii\gii\Module'</span><span>, </span></span></li><li class="alt"><span>        <span class="string">'allowedIPs'</span><span> => [</span><span class="string">'127.0.0.1'</span><span>, </span><span class="string">'::1'</span><span>] </span></span></li><li><span>    ] </span></li><li class="alt"><span>} </span></li></ol>

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

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

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

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

<ol class="dp-c"><li class="alt"><span><span>yii migrate/create create_user_table </span></span></li></ol>

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

<ol class="dp-c"><li class="alt"><span><span><?php </span></span></li><li><span>  </span></li><li class="alt"><span>    <span class="keyword">use</span><span> yii\db\Schema; </span></span></li><li><span>  </span></li><li class="alt"><span>    <span class="keyword">class</span><span> m140924_153425_create_user_table </span><span class="keyword">extends</span><span> \yii\db\Migration </span></span></li><li><span>    { </span></li><li class="alt"><span>        <span class="keyword">public</span><span> </span><span class="keyword">function</span><span> up() </span></span></li><li><span>        { </span></li><li class="alt"><span>  </span></li><li><span>        } </span></li><li class="alt"><span>  </span></li><li><span>        <span class="keyword">public</span><span> </span><span class="keyword">function</span><span> down() </span></span></li><li class="alt"><span>        { </span></li><li><span>            <span class="func">echo</span><span> </span><span class="string">"m140924_153425_create_user_table cannot be reverted.\n"</span><span>; </span></span></li><li class="alt"><span>  </span></li><li><span>            <span class="keyword">return</span><span> false; </span></span></li><li class="alt"><span>        } </span></li><li><span>} </span></li></ol>

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

<ol class="dp-c"><li class="alt"><span><span class="keyword">public</span><span> </span><span class="keyword">function</span><span> up() </span></span></li><li><span>{ </span></li><li class="alt"><span>    <span class="vars">$this</span><span>->createTable(</span><span class="string">'user'</span><span>, [ </span></span></li><li><span>        <span class="string">'id'</span><span> => Schema::TYPE_PK, </span></span></li><li class="alt"><span>        <span class="string">'username'</span><span> => Schema::TYPE_STRING . </span><span class="string">' NOT NULL'</span><span>, </span></span></li><li><span>        <span class="string">'password_hash'</span><span> => Schema:: TYPE_STRING . </span><span class="string">' NOT NULL'</span><span> </span></span></li><li class="alt"><span>    ], null); </span></li><li><span>} </span></li></ol>

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

<ol class="dp-c"><li class="alt"><span><span class="keyword">public</span><span> </span><span class="keyword">function</span><span> down() </span></span></li><li><span>{ </span></li><li class="alt"><span>    <span class="vars">$this</span><span>->dropTable(</span><span class="string">'user'</span><span>); </span></span></li><li><span>} </span></li></ol>

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

<ol class="dp-c"><li class="alt"><span><span>./yii migrate </span></span></li></ol>

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

<ol class="dp-c"><li class="alt"><span><span>./yii migrate/down </span></span></li></ol>

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

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

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

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

<ol class="dp-c"><li class="alt"><span><span class="keyword">return</span><span> [ </span></span></li><li><span>    <span class="comment">// ...</span><span> </span></span></li><li class="alt"><span>    <span class="string">'components'</span><span> => [ </span></span></li><li><span>        <span class="comment">// ...</span><span> </span></span></li><li class="alt"><span>        <span class="string">'db'</span><span> => [ </span></span></li><li><span>            <span class="comment">// ...</span><span> </span></span></li><li class="alt"><span>            <span class="string">'enableSchemaCache'</span><span> => true, </span></span></li><li><span>            <span class="string">'schemaCacheDuration'</span><span> => 3600, </span></span></li><li class="alt"><span>            <span class="string">'schemaCache'</span><span> => </span><span class="string">'cache'</span><span>, </span></span></li><li><span>        ], </span></li><li class="alt"><span>        <span class="string">'cache'</span><span> => [ </span></span></li><li><span>            <span class="string">'class'</span><span> => </span><span class="string">'yii\caching\FileCache'</span><span>, </span></span></li><li class="alt"><span>        ], </span></li><li><span>    ], </span></li><li class="alt"><span>]; </span></li></ol>

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

<ol class="dp-c"><li class="alt"><span><span>./yii asset/template config.php </span></span></li></ol>

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

<ol class="dp-c"><li class="alt"><span><span><?php </span></span></li><li><span>    <span class="keyword">return</span><span> [ </span></span></li><li class="alt"><span>        <span class="string">'jsCompressor'</span><span> => </span><span class="string">'java -jar compiler.jar --js {from} --js_output_file {to}'</span><span>, </span></span></li><li><span>        <span class="string">'cssCompressor'</span><span> => </span><span class="string">'java -jar yuicompressor.jar --type css {from} -o {to}'</span><span>, </span></span></li><li class="alt"><span>        <span class="string">'bundles'</span><span> => [ </span></span></li><li><span>            <span class="comment">// 'yii\web\YiiAsset',</span><span> </span></span></li><li class="alt"><span>            <span class="comment">// 'yii\web\JqueryAsset',</span><span> </span></span></li><li><span>        ], </span></li><li class="alt"><span>        <span class="string">'targets'</span><span> => [ </span></span></li><li><span>            <span class="string">'app\config\AllAsset'</span><span> => [ </span></span></li><li class="alt"><span>                <span class="string">'basePath'</span><span> => </span><span class="string">'path/to/web'</span><span>, </span></span></li><li><span>                <span class="string">'baseUrl'</span><span> => </span><span class="string">''</span><span>, </span></span></li><li class="alt"><span>                <span class="string">'js'</span><span> => </span><span class="string">'js/all-{hash}.js'</span><span>, </span></span></li><li><span>                <span class="string">'css'</span><span> => </span><span class="string">'css/all-{hash}.css'</span><span>, </span></span></li><li class="alt"><span>            ], </span></li><li><span>        ], </span></li><li class="alt"><span>        <span class="string">'assetManager'</span><span> => [ </span></span></li><li><span>            <span class="string">'basePath'</span><span> => __DIR__, </span></span></li><li class="alt"><span>            <span class="string">'baseUrl'</span><span> => </span><span class="string">''</span><span>, </span></span></li><li><span>        ], </span></li><li class="alt"><span>    ]; </span></li></ol>

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

<ol class="dp-c"><li class="alt"><span><span>yii asset config.php /app/assets_compressed.php </span></span></li></ol>

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

<ol class="dp-c"><li class="alt"><span><span class="string">'components'</span><span> => [ </span></span></li><li><span>    <span class="comment">// ...</span><span> </span></span></li><li class="alt"><span>    <span class="string">'assetManager'</span><span> => [ </span></span></li><li><span>        <span class="string">'bundles'</span><span> => </span><span class="keyword">require</span><span> </span><span class="string">'/app/assets_compressed.php'</span><span> </span></span></li><li class="alt"><span>    ] </span></li><li><span>] </span></li></ol>

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

总结

跟任何好的框架类似,Yii可以帮助你快速的创建现代的web应用程序,并确保它们表现的良好. 它能通过为你代劳一些体力活,来促使你创建安全并且可测试的网站. 你可以简单的使用到他们所提供的大多数特性,或者你也可以修改它们以适应你自己的需要. 我真心鼓励你在你的下一个web项目中能试上它一试!

你尝试过 Yii 2 么? 你将会尝试它么? 让我们了解下吧!

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/915116.htmlTechArticle选择 Yii 2 框架的 7 个理由 去年,SitePoint网站发布了一篇文章重点介绍了一些顶尖的PHP开发框架。 排名第四的是Yii发音同Yee)框架。 那时...
Statement:
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