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;
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__];
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 .'"' : ''; } }
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:
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' ] ] ];
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', ], ], ];
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'));
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, ] ];
为了防止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'=> ['@'] ] ] ]; } // ... }
上面的代码用于区分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'] ] }
这样就可以确保党Yii的环境设置为开发的时候,Gii仅支持加载,并且它只通过本地主机访问时才会加载。
现在,让我们来看下模型生成器吧:
表名使用的是一个预输入控件,来试图猜测哪个表格与你的模型相关联,并且所有领域都有一个翻转工具,提示你如何填写出来。在用Gii生成它之前,你可以预览代码,并且所有代码模板是完全可以自定义的。
还有几个命令行工具可以帮你为你的自动化测试创建数据库迁移,信息翻译(I18N:国际化)和数据库fixtures 代码模板。例如,你可以使用如下命令创建一个新的数据库迁移文件:
yii migrate/create create_user_table
这将会在 {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; } }
所以我们可以说,我想添加在该表中再添加几列。我只想添加以下内容到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); }
然后,保证我可以反向迁移,下面我将添加down 方法:
public function down() { $this->dropTable('user'); }
创建该表将会简单包括一个在运行在命令行的命令:
./yii migrate
然后移除该表:
./yii migrate/down
7、容易调整为最佳性能
大家都知道,一个网站很慢的话会很容易让用户产生不满,所以Yii提供了几种工具来帮助你从应用中“挤”出更多的速度。
所有Yii的缓存组件都是从yii/caching/Cache扩展来的,你可以选择任何一种,你想同时使用一个通用API扩展的缓存系统。你甚至可以注册多个高速缓存组件。Yii目前支持数据库和文件缓存,APC,Memcache, Redis, WinCache, XCache和Zend 数据缓存。
默认情况下,如果你正在使用Active Record,然后Yii会运行一个额外的查询,来确定表参与生成模型的架构。你可以通过编辑注配置文件设置应用程序,从而缓存这些架构:
return [ // ... 'components' => [ // ... 'db' => [ // ... 'enableSchemaCache' => true, 'schemaCacheDuration' => 3600, 'schemaCache' => 'cache', ], 'cache' => [ 'class' => 'yii\caching\FileCache', ], ], ];
最后,Yii有一个命令行工具,使前端资源极简化更容易。只需运行以下命令来生成配置模板:
./yii asset/template config.php
然后,编辑该配置来指定工具,达到你想要的简化效果(如关闭编译器, YUI Compressor,或UglifyJS)。生成的配置模板,如下所示:
<?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' => '', ], ];
接着,运行此控制台命令来实现压缩:
'components' => [ // ... 'assetManager' => [ 'bundles' => require '/app/assets_compressed.php' ] ]
注意:你必须要手动下载和安装这些外部工具。
结论:
像任何一个好的框架一样,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!