yii2框架

Late last year, SitePoint published an article highlighting the top PHP frameworks. Tied for the number four spot was the Yii (pronounced Yee) Framework. At that time the latest version of the framework available was 1.1.14. Recently, Yii 2.0 was made available, so you can begin to use it in production.

去年底,SitePoint发表了一篇文章,重点介绍了顶级PHP框架。 排名第四的是Yii(发音为Yee )框架。 当时可用的框架的最新版本是1.1.14。 最近,Yii 2.0可用了,因此您可以开始在生产中使用它。

While we did cover it recently when it was still in RC status, it just reached full release status, and we feel like it’s time to revisit the topic with some reasons for choosing it over alternatives.

虽然我们最近在仍处于RC状态时进行了介绍,但它刚刚达到完全发布状态,并且我们认为是时候重新讨论该主题了,出于某些原因而不是其他选择。

1.易于安装 (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.

对于Web开发人员来说,时间就是金钱,没有人愿意将宝贵的时间花在复杂的安装和配置过程上。

Installation is handled using Composer. If you want a description of the installation process, Sitepoint recently published a great article here. I tend to favor using the basic application template, even when my site has a separate front- and backend component. Instead, I opt to use a Module for the backend portion of my sites. (Yii Modules are best described as mini-applications which reside inside your main application).

使用Composer处理安装。 如果您需要安装过程的描述,Sitepoint最近在这里发表了一篇很棒的文章。 我倾向于使用基本的应用程序模板,即使我的站点具有独立的前端和后端组件也是如此。 相反,我选择对网站的后端部分使用模块 。 (Yii模块最好描述为驻留在主应用程序内部的微型应用程序)。

Note: Many of the directory references in later examples use the directory structure from the simple template.

注意 :后面示例中的许多目录引用都使用简单模板中的目录结构。

2.利用现代技术 (2. Utilizes Modern Technologies)

Yii is a pure OOP framework, and takes advantage of some of PHP’s more advanced features, including late static binding, SPL classes and interfaces, and anonymous functions.

Yii是一个纯OOP框架,并利用了PHP的一些更高级的功能,包括后期静态绑定 , SPL类和接口以及匿名函数 。

All classes are namespaced, which allows you to take advantage of their PSR-4 compliant autoloader. That means that including Yii’s HTML helper class is as simple as:

所有类都有名称空间,这使您可以利用它们的PSR-4兼容自动加载器。 这意味着包括Yii的HTML helper类非常简单:

use yii\helpers\Html;

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

Yii还允许您定义别名以帮助简化名称空间。 在上面的示例中, use语句将加载一个类定义,该类定义默认位于目录/vendor/yiisoft/yii2/helpers 。 此别名在第79行的BaseYii类中定义:

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

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

框架本身及其扩展都是使用Composer安装的。 甚至发布扩展程序的过程都非常容易,就像创建自己的composer.json ,在Github上托管代码并将扩展程序列出在Packagist上一样容易。

3.高度可扩展 (3. Highly Extensible)

Yii is like a suit that looks great off of the rack, but is also very easy to tailor to fit your needs. Virtually every component of the framework is extensible. A simple example is the addition of a unique body ID to your views. (In case you’re interested in knowing why you might want to do this, take a look at this article).

Yii就像一套西装,看起来非常好用,但也很容易量身定制以满足您的需求。 实际上,框架的每个组件都是可扩展的。 一个简单的示例是在视图中添加唯一的主体ID。 (如果您有兴趣知道为什么要这样做,请看一下本文 )。

First, I would create a file in my app\components directory with the name View.php, and add the following:

首先,我将在app\components目录中创建一个名为View.php ,并添加以下内容:

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 would add the following to the body tag of my HTML:

然后,在我的主布局文件( app\views\layouts\main.php )中,将以下内容添加到HTML的body标签中:

<body <?=$this->BodyIdAttribute?>>

And finally, I would add the following to my main configuration file to let Yii know to use my extended View class instead of its own default:

最后,我将以下内容添加到我的主配置文件中,以让Yii知道使用扩展的View类而不是其自己的默认类:

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

4.鼓励测试 (4. Encourages Testing)

Yii is tightly integrated with Codeception. Codeception is a great PHP testing framework that helps simplify the process of creating unit, functional and acceptance tests for your application. Because you ARE writing automated tests for all your applications, right?

Yii与Codeception紧密集成。 Codeception是一个很棒PHP测试框架,可帮助简化为应用程序创建单元测试,功能测试和验收测试的过程。 因为您正在为所有应用程序编写自动化测试,对吗?

The Codeception extension makes it simple to configure your application during testing. Simply edit the provided /tests/_config.php file to configure your test application. For example:

Codeception扩展使在测试过程中配置应用程序变得简单。 只需编辑提供的/tests/_config.php文件即可配置测试应用程序。 例如:

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

Using this configuration, the following would happen:

使用此配置,将会发生以下情况:

  1. Any emails sent during your functional and acceptance tests would be written to a file instead of being sent.在功能测试和验收测试期间发送的所有电子邮件都将被写入文件,而不是被发送。
  2. The URLs in your tests would take on the format index.php/controller/action rather than /controller/action

    测试中的URL的格式应为index.php/controller/action而不是/controller/action

  3. Your tests would use your test database, rather than your production database.您的测试将使用测试数据库,而不是生产数据库。

A special module for the Yii Framework also exists within Codeception. It adds several methods to the TestGuy class, which help you work with Active Record (Yii’s ORM) during functional tests. For instance, if you wanted to see if your registration form successfully created a new User with the username “testuser”, you could do the following:

Yii框架的特殊模块也存在于Codeception中。 它向TestGuy类添加了几种方法,可帮助您在功能测试期间使用Active Record (Yii的ORM)。 例如,如果您想查看您的注册表单是否成功创建了一个名为“ testuser”的新User ,则可以执行以下操作:

$I->amOnPage('register');
$I->fillField('username', 'testuser');
$I->fillField('password', 'qwerty');
$I->click('Register');
$I->seeRecord('app\models\User', array('name' => 'testuser'));

5.简化安全性 (5. Simplifies Security)

Security is a crucial part of any web application, and fortunately Yii has some great features to help ease your mind.

安全性是任何Web应用程序中至关重要的部分,幸运的是Yii具有一些出色的功能来帮助您放心。

Yii comes with a Security application component that exposes several methods to help assist in creating a more secure application. Some of the more useful methods are:

Yii带有一个安全应用程序组件,该组件公开了几种方法来帮助创建更安全的应用程序。 一些更有用的方法是:

  • generatePasswordHash: Generates a secure hash from a password and a random salt. This method makes a random salt for you, and then creates a hash from the supplied string using PHP’s crypt function.

    generatePasswordHash :从密码和随机盐生成安全哈希。 该方法为您制作了一个随机盐,然后使用PHP的crypt函数从提供的字符串中创建哈希。

  • validatePassword: This is the companion function to generatePasswordHash, and allows you to check whether the user supplied password matches your stored hash.

    validatePassword :这是generatePasswordHash的配套函数,可让您检查用户提供的密码是否与您存储的哈希匹配。

  • generateRandomKey: Allows you to create a random string of any length

    generateRandomKey :允许您创建任意长度的随机字符串

Yii automatically checks for a valid CSRF token on all unsafe HTTP request methods (PUT, POST, DELETE), and will generate and output a token when you use the ActiveForm::begin() method to create your opening form tag. This feature can be disabled by editing your main configuration file to include the following:

Yii会自动检查所有不安全的HTTP请求方法(PUT,POST,DELETE)上的有效CSRF令牌,并在您使用ActiveForm :: begin()方法创建打开表单标签时生成并输出一个令牌。 可以通过编辑主配置文件以包括以下内容来禁用此功能:

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

In order to protect against XSS, Yii provides another helper class called HtmlPurifier. This class has a single static method named process, and will filter your output using the popular filter library of the same name.

为了防止XSS,Yii提供了另一个名为HtmlPurifier的帮助程序类。 此类具有一个名为process的静态方法,它将使用流行的相同名称的过滤器库过滤您的输出。

Yii also includes ready-to-use classes for user authentication and authorization. Authorization is broken into two types: ACF (Access Control Filters) and RBAC (Role-Based Access Control).

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

The simpler of the two is ACF, and is implemented by adding the following to the behaviors method of your controller:

两者中最简单的是ACF,是通过将以下内容添加到控制器的behaviors方法中来实现的:

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 preceding code tells DefaultControllerto allow guest users to access the login and view actions, but not the create action. (? is an alias for anonymous users, and @ refers to authenticated users).

上面的代码告诉DefaultController允许来宾用户访问loginview操作,但不允许访问create操作。 ( ?是匿名用户的别名, @经过身份验证的用户)。

RBAC is a more powerful method of specifying which users can perform specific actions throughout your application. It involves creating roles for your users, defining permissions for your app, and then enabling those permissions for their intended roles. You could use this method if you wanted to create a Moderator role, and allow all users assigned to this role to approve articles.

RBAC是一种更强大的方法,用于指定哪些用户可以在整个应用程序中执行特定的操作。 它涉及为用户创建角色,为您的应用定义权限,然后为其预期角色启用这些权限。 如果要创建Moderator角色,并允许分配给该角色的所有用户批准文章,则可以使用此方法。

You can also define rules using RBAC, which allow you, under specific conditions, to grant access to certain aspects of your application. For instance, you could create a rule that allows users to edit their own articles, but not those created by others.

您还可以使用RBAC定义规则,该规则允许您在特定条件下授予对应用程序某些方面的访问权限。 例如,您可以创建一个规则,该规则允许用户编辑自己的文章,但不能编辑其他人创建的文章。

6.缩短开发时间 (6. Shorten Development Time)

Most projects involve a certain amount of repetitive tasks that no one wants to waste time with. Yii gives us a few tools to help you spend less time on those tasks, and more time customizing your application to suit your clients’ needs.

大多数项目都涉及一定数量的重复性任务,没有人愿意浪费时间。 Yii提供了一些工具来帮助您减少在这些任务上的时间,而将更多时间用于定制应用程序以满足客户的需求。

One of the most powerful of these tools is called “Gii”. Gii is a web-based code scaffolding tool, which allows you to quickly create code templates for:

这些工具中最强大的工具之一就是“ Gii”。 Gii是基于Web的代码脚手架工具,可让您快速创建以下代码模板:

  • Models楷模
  • Controllers控制器
  • Forms形式
  • Modules模组
  • Extensions扩展名
  • CRUD controller actions and viewsCRUD控制器操作和视图

Gii is highly configurable. You can set it to only load in certain environments. Simply edit your web configuration file as follows:

Gii是高度可配置的。 您可以将其设置为仅在某些环境中加载。 只需按如下所示编辑您的Web配置文件:

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

This ensures that Gii will only load when the Yii environment variable is set to development, and that it will only load when accessed via localhost.

这样可以确保Gii仅在Yii环境变量设置为development时加载,并且仅在通过localhost访问时才加载。

Now let’s take a look at the model generator:

现在让我们看一下模型生成器:

The table name uses a typeahead widget to try to guess which table your model is associated with, and all fields have a rollover tooltip to remind you how to fill them out. You can preview code before you ask Gii to generate it, and all the code templates are completely customizable.

该表名称使用一个typeahead小部件来尝试猜测您的模型与哪个表相关联,并且所有字段都有一个过渡工具提示,以提醒您如何填写它们。 您可以在要求Gii生成代码之前预览代码,并且所有代码模板都是完全可定制的。

There are also several command-line tools available to help create code templates for database migrations, message translations (I18N) and database fixtures for your automated tests. For instance, you can create a new database migration file with this command:

还有一些命令行工具可用来帮助创建用于数据库迁移,消息翻译(I18N)的代码模板以及用于自动化测试的数据库固定装置。 例如,您可以使用以下命令创建新的数据库迁移文件:

yii migrate/create create_user_table

This will create a new migration template in {appdir}/migrations that looks something like this:

这将在{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;
}
}

So let’s say I wanted to add a few columns to this table. I would simply add the following to the up method:

假设我想在此表中添加几列。 我只需将以下内容添加到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);
}

And then to make sure I can reverse the migration, I would edit the down method:

然后为确保我可以撤消迁移,我将编辑down方法:

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

Creating the table would simply involve running a command on the command line:

创建表仅涉及在命令行上运行命令:

./yii migrate

and to remove the table:

并删除表:

./yii migrate/down

7.易于调整以获得更好的性能 (7. Easy to Tune for Better Performance)

Everybody knows that a slow website creates disgruntled users, so Yii provides you with several tools to help you squeeze more speed out of your application.

每个人都知道,缓慢的网站会导致用户不满,因此Yii为您提供了多种工具来帮助您提高应用程序的速度。

All Yii’s cache components extend from yii/caching/Cache, which allows you to choose whichever caching system you want while using a common API. You can even register multiple cache components simultaneously. Yii currently supports database and file system caching, as well as APC, Memcache, Redis, WinCache, XCache and Zend Data Cache.

Yii的所有缓存组件都从yii / caching / Cache扩展而来,它使您可以在使用通用API时选择所需的任何缓存系统。 您甚至可以同时注册多个缓存组件。 Yii当前支持数据库和文件系统缓存,以及APC,Memcache,Redis,WinCache,XCache和Zend Data Cache。

By default, if you’re using Active Record then Yii runs an extra query to determine the schema of the table(s) involved in generating your model. You can set the application to cache these schema by editing your main configuration file as follows:

默认情况下,如果您使用的是Active Record,则Yii将运行一个额外的查询,以确定生成模型所涉及的表的模式。 您可以通过编辑主配置文件来将应用程序设置为缓存这些架构,如下所示:

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

Finally, Yii has a command line tool to facilitate the minification of frontend assets. Simply run the following command to generate a configuration template:

最后,Yii提供了一个命令行工具来促进前端资产的最小化。 只需运行以下命令即可生成配置模板:

./yii asset/template config.php

Then edit the configuration to specify which tools you want to you perform your minification (e.g. Closure Compiler, YUI Compressor, or UglifyJS). The generated configuration template will look like this:

然后编辑配置以指定要执行缩小的工具(例如Closure Compiler,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' => '',
],
];

Next, run this console command in order to perform the compression.

接下来,运行此控制台命令以执行压缩。

yii asset config.php /app/assets_compressed.php

And finally, edit your web application configuration file to use the compressed assets.

最后,编辑您的Web应用程序配置文件以使用压缩资产。

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

Note: You will have to download and install these external tools manually.

注意:您将必须手动下载并安装这些外部工具。

结论 (Conclusion)

Like any good framework, Yii helps you create modern web applications quickly, and make sure they perform well. It pushes you to create secure and testable sites by doing a lot of the heavy lifting for you. You can easily use most of its features exactly as they are provided, or you can modify each one to suit your needs. I really encourage you to check it out for your next web project!

与任何好的框架一样,Yii可以帮助您快速创建现代Web应用程序,并确保它们表现良好。 它通过为您做很多繁重的工作来促使您创建安全且可测试的站点。 您可以完全按照其提供的功能轻松使用其大多数功能,也可以根据自己的需要进行修改。 我非常鼓励您检查下一个Web项目!

Have you tried Yii 2? Will you? Let us know!

您是否尝试过Yii 2? 你会? 让我们知道!

翻译自: https://www.sitepoint.com/7-reasons-choose-yii-2-framework/

yii2框架

yii2框架_选择Yii 2框架的7个理由相关推荐

  1. node mysql框架_关于nodejs的框架选择

    对于新入门的小伙伴来说,选择一个合适的nodejs框架可能是一件很头疼的事情,我最初也为这个头疼过,下面分享一下我的框架选择之路 nodejs的框架 最近来node的火热,带动了一大批的框架,例如 e ...

  2. java 轻量级插件化框架_轻量级插件化框架——Small

    photo-1441716844725-09cedc13a4e7.jpg 前言 世界那么大,组件那么小.Small,做最轻巧的跨平台插件化框架. --Galenlin 这是Small作者,林光亮老师, ...

  3. java mysql orm框架_主流 Java ORM 框架有哪些?

    主流 Java ORM 框架有哪些? ORM 是 Object Relational Mapping 的缩写,译为 "对象关系映射" 框架. 所谓的 ORM 框架就是一种为了解决面 ...

  4. .net core orm框架_轻量级高性能PHP框架ycroute

    YCRoute 目录 框架介绍 运行环境 代码结构 路由配置 过滤验签 控制层 加载器 模型层 数据交互dao层(可选) Redis缓存操作 数据库操作 配置加载 公共类加载 公共函数 日志模块 视图 ...

  5. 分布式事务框架_阿里分布式事务框架GTS开源啦!

    点击上方"Java后端技术",选择"置顶或者星标" 每天带你看高清大图哦! 整理:开源中国 就在9号这天,阿里分布式事务框架GTS开源了一个免费社区版Fesca ...

  6. python分布式框架_高性能分布式执行框架——Ray

    Ray是UC Berkeley RISELab新推出的高性能分布式执行框架,它使用了和传统分布式计算系统不一样的架构和对分布式计算的抽象方式,具有比Spark更优异的计算性能. Ray目前还处于实验室 ...

  7. android 富文本框架_当微擎框架遇上uniapp,以一当十同时开发十个平台项目

    随着各类平台异军突起,流量也越来越分散.为了适应时代的发展,不少公司在做产品项目的时候,需要例如网站.公众号.H5.微信小程序.抖音小程序.支付宝小程序.百度小程序.360小程序.快应用.安卓app. ...

  8. unity技能框架_如何使用指导框架学习新技能

    unity技能框架 Last October I created a Mentoring Framework at work. The goal was to create a project fro ...

  9. 苹果多开框架_苹果暴露通知框架的旅程以及如何使用它

    苹果多开框架 In early March the nonprofit association Novid20 was founded aiming to find and implement sol ...

最新文章

  1. 资源 | 机器学习、NLP、Python和Math最好的150余个教程(建议收藏)
  2. linux 连接远程命令行,screen命令行远程连接
  3. python【蓝桥杯vip练习题库】ALGO-91 Anagrams问题
  4. select ...as_一起使用.select .map和.reduce方法可充分利用Ruby
  5. linux怎么看文件状态,linux查看文件类型-file、状态-stat
  6. g100显卡 linux驱动,nvidia geforce g100驱动
  7. 进入IT行业,要不要参加培训班?
  8. centos mysql rpm re_CentOS 7 RPM 安装 MySQL5.7
  9. Linux内核:内存从BIOS->e820->memblock->node/zone基本流程
  10. python子窗口返回数据给主窗口_Python Scrapy,从子页面返回进行抓取
  11. 一分钟先生---走出软件作坊:三五个人十来条枪 如何成为开发正规军(三十二)...
  12. I2C详解(2) I2C总线的规范以及用户手册(1) I2C 总线协议
  13. Android Builder模式
  14. 易辅客栈网页游戏脚本实战(绝世仙王)
  15. petalinux 安装
  16. Java中undefined是什么意思,Haskell中的undefined和Java中的null有什么区别?
  17. ML1.1 机器学习误差分析
  18. 微信第三方登录,主要手机没有安装微信处理
  19. Java 集合 --- String, StringBuilder, StringBuffer
  20. 基于TLE6220GP的开关电磁阀驱动电路

热门文章

  1. StopWatch计时器
  2. JAVA-File类与IO流
  3. 华为手机使用应用沙盒一键修改电池信息
  4. 电脑右键没有“发送到”选项
  5. 异常java.lang.IllegalArgumentException: Validation failed for query for method public abstract
  6. 【自学宝典】从零开始自学网络安全,按照这个路线就可以了
  7. 在docker里跑gpgpusim
  8. 找回你的xournal++未保存文档
  9. chiplogic-网表提取-(2)二极管三极管电阻器件插入
  10. selenium 获取元素getAttribute(“innerHTML“)和getAttribute(“outerHTML“)的区别