yii2 v2.0.15
Yii 2.0 was released into beta last April and the goal for a first stable release was set for the middle of 2014. The GitHub issue list has 300 open issues and 2913 closed while I’m writing this and both numbers are still increasing. The progress to the 2.0RC milestone was at 99%. My guess is that the team is close, but we’ll probably have to wait just a little bit longer. While we’re all waiting, lets take a look at what we can expect by looking at an already available example.
Yii 2.0于去年4月发布到beta中,第一个稳定版本的目标定于2014年中。GitHub问题列表中有300个未解决问题,而2913个已关闭,而我正在撰写此文,而且两个数字还在不断增加。 达到2.0RC里程碑的进度为99%。 我的猜测是团队很亲密,但是我们可能不得不再等一会儿。 当我们都在等待的时候,让我们通过查看一个已经可用的示例来看看我们可以期待什么。
一点点的历史 (A tiny bit of history)
The first version of Yii became popular quite fast after it was released in 2008. It’s founder, Qiang Xue, previously worked on the Prado framework and used experience and feedback from that to build Yii.
Yii的第一个版本在2008年发布后Swift流行。它的创始人Qiang Xue曾在Prado框架上工作,并利用经验和反馈来构建Yii。
Yii uses many ideas from other frameworks, languages and libraries: Prado, Ruby, jQuery, Symfony and Joomla are all acknowledged as sources of inspiration.
Yii使用来自其他框架,语言和库的许多想法:Prado,Ruby,jQuery,Symfony和Joomla都被认为是灵感的来源。
The first commits for Yii 2.0 date back to 2011 but the development picked up last year. The team did a rewrite with an aim to become the state of the art new generation PHP framework. It adopts the latest technologies and features, such as Composer, PSR, namespaces, traits, and more.
Yii 2.0的第一次提交可以追溯到2011年,但去年得到了发展。 该团队进行了重写,旨在成为最先进的新一代PHP框架。 它采用了最新的技术和功能,例如Composer,PSR,名称空间,特征等。
Something worth mentioning is that according to the download page Yii version 1.1 support will end on December 31, 2015, so we do get some time to start thinking about making the transition.
值得一提的是,根据下载页面的 Yii版本1.1支持将在2015年12月31日终止,因此我们确实有一些时间开始考虑进行过渡。
要求 (Requirements)
The usage of namespaces and traits upped the requirements to PHP 5.4. Additionally, you’ll need the mb_string, PDO and intl extensions when you start developing. This should not be a problem if you run your own server, but might be if you’re on a shared environment. Of course, in time, that issue will disappear.
命名空间和特征的使用将要求提高到PHP 5.4。 另外,在开始开发时,您将需要mb_string,PDO和intl扩展。 如果您运行自己的服务器,这应该不是问题,但是如果您在共享环境中,则可能是问题。 当然,随着时间的流逝,这个问题将消失。
安装 (Installation)
Yii is now installable from Composer. We’ll go through this installation method soon.
现在可以从Composer安装Yii。 我们将很快介绍这种安装方法。
Currently, there are two application examples available. There is a basic example containing a few pages, a contact page and a login page. The advanced example adds a separate front and backend, database interaction, signup and password recovery.
当前,有两个应用示例可用。 有一个基本示例,包含几个页面,一个联系页面和一个登录页面。 这个高级示例添加了一个单独的前端和后端,数据库交互,注册和密码恢复。
入门 (Getting started)
I’ll start with the basic example. If you’ve looked at Yii before, you’ll recognize the same basic webapp that Yii 1.1 came with. Install the basic example with Composer using the following command:
我将从基本示例开始。 如果您以前看过Yii,将会认识到Yii 1.1附带的相同基本Web应用程序。 使用以下命令通过Composer安装基本示例:
composer.phar create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic
You can then check if your server meets the requirements by opening up http://localhost/yii2-app-basic/requirements.php. The actual application will then run from http://localhost/yii2-app-basic/web/.
然后,您可以通过打开http://localhost/yii2-app-basic/requirements.php来检查服务器是否满足要求。 然后,实际的应用程序将从http:// localhost / yii2-app-basic / web /运行 。
This is the first important thing to notice: the idea is that you set the document root of your application to the /path/to/application/web
, much like with Symfony. The directory layout changed a bit from version 1.1. If you look closely, the change makes sense and will improve the security of your application.
这是要注意的第一件事:想法是将应用程序的文档根目录设置为/path/to/application/web
,就像Symfony一样。 目录布局与1.1版相比有所变化。 如果您仔细观察,所做的更改将是有意义的,并且将提高应用程序的安全性。
Previously, all the application components (models, views, controllers, framework and vendor libraries) would live under the document root in the protected
folder. That way the security depended on .htaccess
files to be respected, which meant your application was 100% insecure by default on Nginx. Moving all the application components away from the document root prevents the web server from sending your application components to a user.
以前,所有应用程序组件(模型,视图,控制器,框架和供应商库)都将位于protected
文件夹的文档根目录下。 这样,安全性就取决于要遵守的.htaccess
文件,这意味着您的应用程序默认在Nginx上是100%不安全的。 将所有应用程序组件从文档根目录移开会阻止Web服务器将应用程序组件发送给用户。
You might find yourself looking for the actual framework sources. The framework is a component that was installed using Composer, so it’ll reside under the vendor\yiisoft\yii
directory. Here you’ll find a lot more, but for now, we’ll just leave it at that.
您可能会发现自己正在寻找实际的框架资源。 该框架是使用Composer安装的组件,因此它将位于vendor\yiisoft\yii
目录下。 在这里,您会找到更多,但就目前而言,我们将其保留。
For now, let’s change the local web server configuration and set the document root to /path/to/application/web
. I added a virtualhost http://yii2-app-basic.localhost/, but do as you see fit for your own situation. The default configuration is set to hide the script file in the URL. If you’re using Apache, you’ll need to add an .htaccess
file to the web directory to instruct Apache to do rewriting, it’s not there by default.
现在,让我们更改本地Web服务器配置,并将文档根目录设置为/path/to/application/web
。 我添加了一个虚拟主机http://yii2-app-basic.localhost/ ,但您认为适合自己的情况。 默认配置设置为在URL中隐藏脚本文件。 如果您使用的是Apache,则需要向Web目录中添加.htaccess
文件以指示Apache进行重写,默认情况下该文件不存在。
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
看看基本的Yii应用程序 (A look at the basic Yii application)
Now that we have the basic application running, some congratulations are in order…
既然我们已经运行了基本应用程序,那么一定要恭喜一些……
![title Yii2_installed.png](https://uploads.sitepoint.com/wp-content/uploads/2014/08/1408461409Yii2_installed.png)
Thanks! No rocket science so far.
谢谢! 到目前为止,还没有火箭科学。
You’ll start with start page, a static about page, a contact page and a login page. The contact page and login form have the same functionality available as before; captcha code, form validation and two users available for logging in. Logging in does the same as before; close to nothing. Still, it is a good start.
您将从开始页面,静态关于页面,联系页面和登录页面开始。 联系人页面和登录表单具有与以前相同的功能; 验证码,表单验证和两个可供登录的用户。 几乎没有。 不过,这是一个良好的开始。
The design of the basic application changed dramatically. Previously you’d get an application built on the Blueprint CSS framework whereas now we start off with Twitter Bootstrap. Improvement? It probably is compared to Blueprint, but then again Bootstrap is a lot more than Blueprint ever tried to be. Bootstrap will give you all sorts of application components and will speed up building an application. Some might argue on the other hand that all sites look the same with Bootstrap (themes only fix this partially) and it will also make your site larger size-wise. Either way, the integration with Yii 2.0 is done with the yii2-bootstrap extension. This makes it very easy to integrate the Bootstrap components in your views.
基本应用程序的设计发生了巨大变化。 以前,您将获得一个基于Blueprint CSS框架构建的应用程序,而现在,我们将从Twitter Bootstrap开始。 有改善吗? 它可能与Blueprint进行了比较,但是Bootstrap再次比Blueprint尝试的要多得多。 Bootstrap将为您提供各种应用程序组件,并加快构建应用程序的速度。 另一方面,有人可能会争辩说,所有站点在Bootstrap上看起来都是一样的(主题仅部分修复了此问题),这也会使您的站点在规模上更大。 无论哪种方式,都可以通过yii2-bootstrap扩展与Yii 2.0集成。 这使得在您的视图中集成Bootstrap组件非常容易。
Another thing you’ll notice is the debug bar at the bottom. It is installed and activated by default, just like in Symfony. It allows for quick access to loads of information about your configuration, requests and application logging. It’ll keep a history of requests with debug information as well.
您会注意到的另一件事是底部的调试栏。 就像在Symfony中一样,它是默认安装和激活的。 它允许快速访问有关您的配置,请求和应用程序日志记录的信息。 它还将保留带有调试信息的请求历史记录。
![title Yii2 debugger](https://i-blog.csdnimg.cn/blog_migrate/e1654195ac3ec9c42dd6430aed7a33ee.webp?x-image-process=image/format,png)
Yii handles errors different than PHP normally would. Yii converts all errors (fatal and non-fatal) to exceptions. Those are handled by rendering an insightful output pointing you towards the point where you messed up or your code generated a notice. Even parse errors, for which Yii 1.1 would fall back to the basic PHP errors, get a nicely rendered overview of your code. This is something most of us will appreciate.
Yii处理的错误与PHP通常不同。 Yii将所有错误(致命和非致命)转换为异常。 通过呈现有洞察力的输出来处理这些问题,这些输出将您引向您陷入困境或代码生成通知的地方。 甚至解析错误(Yii 1.1都将其归结为基本PHP错误)也可以很好地呈现代码概述。 这是我们大多数人都会欣赏的东西。
![title Yii2 error handling](https://uploads.sitepoint.com/wp-content/uploads/2014/08/1408964657Yii2_errorhandling.png)
Gii is also present again and activated by default.
Gii也再次出现并默认激活。
![title Yii2 Gii](https://uploads.sitepoint.com/wp-content/uploads/2014/08/1408965458Yii2_gii.png)
Gii will help you by generating code for you to start with, another great tool to help speed up your development. It will generate models and controllers for you. The CRUD generator will go one step further and generate a complete MVC set for all the actions. Gii will also generate code better suited for Internationalization (i18n) by immediately inserting the Yii::t()
function where you’ll need it.
Gii将通过为您生成代码来帮助您,这是另一个有助于加快开发速度的出色工具。 它将为您生成模型和控制器。 CRUD生成器将更进一步,并为所有操作生成完整的MVC集。 Gii还将通过立即在需要的地方插入Yii::t()
函数来生成更适合国际化(i18n)的代码。
The basic application now also comes with a simple command line application which you can build upon. Yii 1.1 already supported this but you’d have to get an example from the Wiki.
现在,基本应用程序还带有一个可以构建的简单命令行应用程序。 Yii 1.1已经支持此功能,但是您必须从Wiki获得示例。
That’s what you’ll find in the basic application. There is also an advanced application example available. It has a somewhat different structure but adds even more functionality to your application out of the box:
这就是您在基本应用程序中找到的内容。 还有一个高级应用示例。 它的结构有些不同,但是为应用程序开箱即用添加了更多功能:
- User authorization, authentication and password restore. 用户授权,身份验证和密码还原。
- An application split into a front and backend. 应用程序分为前端和后端。
Continuing the look at the basic version, let’s take a closer look and dive into the code…
继续看基本版本,让我们仔细看一下并深入研究代码…
发生了什么变化? (What changed?)
A lot has changed. Some changes might confuse you at first, but I find most changes make sense and are easy to accept. Here are some of the changes that I found interesting, fun or puzzling.
发生了很大变化。 一开始有些更改可能会使您感到困惑,但是我发现大多数更改都是合理的并且易于接受。 这是我发现有趣,有趣或令人困惑的一些更改。
The PHP 5.4 requirement made some changes possible; the array short tags are available. It’s also safe to use the echo short tags in views because that doesn’t depend on configuration settings anymore.
PHP 5.4要求使某些更改成为可能。 数组短标签可用。 在视图中使用echo short标签也是安全的,因为它不再依赖于配置设置。
<?php
$elements = array(1,2,3,4); //Yii 1.1
$elements = [1,2,3,4]; //Yii 2.0
?>
<?php echo $someVar; ?> //Yii 1.1
<?= $someVar ?> //always safe to use in Yii 2.0
A small change, but one you’ll run into fast; before, you’d use Yii::app()
to access the application instance and it’s components. In Yii 2.0 this changed from a static function to a static variable Yii::$app
.
很小的变化,但是很快就会遇到。 之前,您将使用Yii::app()
访问应用程序实例及其组件。 在Yii 2.0中,这从静态函数更改为静态变量Yii::$app
。
The translate function Yii::t()
is still with us. It instructs Yii to use the i18n component to translate the supplied text to the current language used. You can also instruct it to substitute variables.
转换函数Yii::t()
仍然存在。 它指示Yii使用i18n组件将提供的文本翻译为当前使用的语言。 您还可以指示它替换变量。
<?php
echo `Yii::t('app', 'Hello, {username}!', [
'username' => $username,
]);
?>
The placeholder formatting and styling has been seriously reworked allowing for more formatting options. Some examples:
占位符的格式和样式已经过认真的重新设计,允许使用更多的格式选项。 一些例子:
<?php
echo \Yii::t('app', '{n, number} is spelled as {n, spellout}', ['n' => 81]);
echo \Yii::t('app', 'You are {n, ordinal} in line, please hold.', ['n' => 3]); //Will echo "You are 3rd in line, please wait.".
echo \Yii::t('app', 'There {n, plural, =0{are no cats} =1{is one cat} other{are # cats}}!', array(
'n' => 14,
));
?>
Because of this placeholder formatting, the DateTimeFormatter is gone:
由于这种占位符格式,DateTimeFormatter消失了:
<?php
//Previously in Yii 1.1
Yii::app()->dateFormatter->formatDateTime(time(), 'medium', 'medium');
//In Yii 2.0
echo \Yii::t('app', 'The date is {0, date, short}', time()); //uses the pre-defined 'short' notation (i18n save)
echo \Yii::t('app', 'The date is {0, date, YYYY-MM-dd}', time()); //or define your own notation
?>
This functionality is supplied by the ICU library. The Yii documentation calls the original documentation for this: “quite cryptic”. I dare you to read it and try to understand it… Let’s hope the Yii documentation includes a more readable version in time.
此功能由ICU库提供。 Yii文档将其称为原始文档 :“相当神秘”。 我敢于您阅读并尝试理解它。希望我们Yii文档能及时包含一个更具可读性的版本。
控制器 (Controllers)
Before, accessControl()
would be a function of your controller if you wanted to use the Yii access control functionality. With Yii 2.0, access control is part of the controllers behavior()
:
以前,如果您想使用Yii访问控制功能, accessControl()
将是您控制器的功能。 在Yii 2.0中,访问控制是控制器behavior()
:
<?php
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout','login','signup'],
'rules' => [
[
'allow' => true,
'actions' => ['logout'],
'roles' => ['@'],
],
[
'allow' => true,
'actions' => ['login', 'signup'],
'roles' => ['?'],
],
],
],
];
}
?>
This is almost identical to the way it was in Yii 1.1.
这几乎与Yii 1.1中的方式相同。
I did notice that the example code (not the framework itself!) is missing many docblocks and has a lot of @inheritdoc comments. This isn’t what you’d expect from an example but I assume that this will be fixed in time.
我确实注意到示例代码(不是框架本身!)缺少许多docblock,并且具有许多@inheritdoc注释。 这不是您希望从示例中得到的结果,但是我认为这将及时得到解决。
楷模 (Models)
The basic model (previously CModel) didn’t change much. Scenarios now allow you to change the enforcement of validation rules. You can change what needs to be validated based on your current scenario (i.e. a model with different rules when used from a front or backend).
基本模型(以前为CModel)变化不大。 现在,方案允许您更改验证规则的实施。 您可以根据当前方案(例如,从前端或后端使用具有不同规则的模型)来更改需要验证的内容。
The derived ActiveRecord underwent some serious changes, though. The syntax for searching with ActiveRecord became more like writing queries because CDbCriteria is gone. It has been replaced by ActiveQuery making retrieving information easier:
但是,派生的ActiveRecord进行了一些重大更改。 使用ActiveRecord进行搜索的语法变得更像编写查询,因为CDbCriteria不见了。 它已被ActiveQuery取代,从而使信息检索更加容易:
<?php
$authors = Authors::find()
->where(['sitepointChannel' => $channel])
->orderBy('lastName')
->all();
?>
Relations definition also changed dramatically. Lets take for example a site with bloggers that post articles on which users comment. The relations definitions for the authors table is described below. I’ll start with how it looked in Yii 1.1:
关系定义也发生了巨大变化。 让我们以一个拥有博客作者的网站为例,该博客发布用户评论的文章。 作者表的关系定义如下所述。 我将从Yii 1.1的外观开始:
<?php
//Define the relations
public function relations()
{
return array(
'posts' => array(self::HAS_MANY, 'Posts', 'authorID'),
'comments' => array(self::HAS_MANY, 'Comments', array('ID'=>'PostID'), 'through'=>'posts'),
);
}
//Querying an author with posts and comments
$activity = Author::model()->with(array('posts','comments')->find('fullname = "Arno Slatius"');
$posts = $activity->posts;
$comments = $activity->comments;
?>
As you can see, you’d define all the relations of an Active record in a large array. In Yii 2.0 you’ll have to define getter methods that return an ActiveQuery object for all those relations. You’d have to use the keyword ‘through’ in a relation to define a relation between an intermediary table.
如您所见,您将在一个大型数组中定义一个Active记录的所有关系。 在Yii 2.0中,您必须定义getter方法,以针对所有这些关系返回ActiveQuery对象。 您必须在关系中使用关键字“直通”来定义中间表之间的关系。
You now have two options to define this; normally you’d use the via()
method in a relation function. You can also define the relation using the viaTable()
method if you only need the data in the table after the pivot table. Same example as above but now for Yii 2.0:
现在,您有两个选择来定义它; 通常,您将在关联函数中使用via()
方法。 如果只需要数据透视表之后的表中的数据,则也可以使用viaTable()
方法定义关系。 与上述示例相同,但现在针对Yii 2.0:
<?php
//Define relations by creating getter functions
public function getPosts()
{
return $this->hasMany(Posts::className(), ['authorID' => 'ID']);
}
public function getComments()
{
return $this->hasMany(Comments::className(), ['ID' => 'PostID'])
->via('Posts');
}
//If you'd only need comments you'd define it at once:
public function getComments()
{
return $this->hasMany(Comments::className(), ['ID' => 'PostID'])
->viaTable(Posts::className(), ['authorID' => 'ID']);
}
//Querying an author with posts and comments
$activity= Authors::findOne(['fullname' => 'Arno Slatius']);
$posts = $activity->posts;
$comments = $activity->comments;
?>
This is a rather simple example. Defining the relations through the getter functions that return ActiveQuery objects allows for much more. You can, for instance, add a specific function that does a query for posts that get >50 comments by adding a where()
call in the returned ActiveQuery.
这是一个相当简单的例子。 通过返回ActiveQuery对象的getter函数来定义关系可以进行更多操作。 例如,您可以添加一个特定的函数,该函数通过在返回的ActiveQuery中添加where()
调用来查询获得50条以上评论的帖子。
An interesting addition is the possibility to define cross DBMS relations. You can define relations between for instance MySQL and MongoDB or Redis and use them in your application as one object.
一个有趣的补充是可以定义跨DBMS关系。 您可以定义例如MySQL和MongoDB或Redis之间的关系,并将它们在应用程序中用作一个对象。
观看次数 (Views)
The main thing to note in views is that $this
doesn’t refer to the controller instance anymore. In a view, $this
is an instance of the yii\web\View
object. The controller is accessible through $this->context
.
视图中要注意的主要事情是$this
不再引用控制器实例。 在视图中, $this
是yii\web\View
对象的实例。 可以通过$this->context
访问控制器。
As I said before; PHP 5.4 makes the short echo tag consistently available. This makes the views which consist of mixed PHP and HTML more readable;
如我之前所说; PHP 5.4使短回显标记始终可用。 这使得包含PHP和HTML的混合视图更加可读。
<h1><?= Html::encode($this->title) ?></h1>
The render()
and renderPartial()
functions changed as well. Before it would echo
the rendered output automatically and you’d have to add an additional parameter to get the rendered output as a string. Yii 2.0 will always return a string on render()
-like calls making it more consistent with the way widgets behave.
render()
和renderPartial()
函数也发生了变化。 在它自动echo
显渲染的输出之前,您必须添加一个附加参数以将渲染的输出作为字符串获取。 Yii 2.0将始终在类似render()
的调用上返回一个字符串,从而使其与小部件的行为方式更加一致。
从Yii 1.1升级 (Upgrading from Yii 1.1)
Should you consider upgrading your Yii 1.1 application to Yii 2.0 in time?
您是否应该考虑将Yii 1.1应用程序及时升级到Yii 2.0?
Bruno Škvorc recently wrote about legacy code here on SitePoint. He argues that a rewrite that can be done in 2 months should be considered – especially if the software you’re using is business critical. I agree with him and would suggest you consider it if you feel seriously about your application and want to maintain it beyond the end of life of Yii 1.1. But as always; it depends on your situation.
BrunoŠkvorc最近在SitePoint上撰写了有关遗留代码的文章。 他认为应该考虑在2个月内完成重写, 尤其是在您使用的软件对业务至关重要的情况下。 我同意他的建议,如果您对自己的应用程序有认真的看法,并希望在Yii 1.1生命周期结束前对其进行维护,建议您考虑使用它。 但是一如既往 这取决于您的情况。
There’s a special page dedicated to upgrading Yii on the Yii website. The biggest problem, for now, are your extensions. If you rely on a lot of extensions, you’ll have a hard time because it’ll take some time for the community to take up (re)writing the extensions for Yii 2.0. If you’re a real pro, you could of course take a serious look at the extensions you’re using and consider (re)writing them.
Yii网站上有一个专门的页面专门用于升级Yii 。 目前最大的问题是扩展。 如果您依赖大量扩展,那么您会很困难,因为社区需要一些时间来(重新)编写Yii 2.0的扩展。 如果您是一名真正的专业人士,那么您当然可以认真考虑所使用的扩展,并考虑(重新)编写它们。
The migration manual has a section on running Yii 1.1 and Yii 2.0 together in an application. For large projects this is a good way to create a safe migration path. Migrate your generic code to Yii 2.0 and take your time on the more complex or extension filled parts.
迁移手册中有一节介绍如何在应用程序中同时运行Yii 1.1和Yii 2.0 。 对于大型项目,这是创建安全迁移路径的好方法。 将您的通用代码迁移到Yii 2.0,并花一些时间在更复杂或扩展填充的部分上。
结论 (Conclusion)
Going over the The Definitive Guide to Yii 2.0 gets me more and more enthusiastic to get started with Yii 2.0. I already had to stop myself from using it in a new project because I couldn’t risk problems with pre-production code.
查看《 Yii 2.0权威指南》使我越来越热衷于开始使用Yii 2.0。 我已经不得不停止在新项目中使用它,因为我无法冒险使用预生产代码。
The documentation quality for Yii 2.0 improved from Yii 1.1. I had a hard time figuring stuff out when I started with Yii 1.1 a few years ago and I feel the documentation is more extensive than before.
Yii 2.0的文档质量比Yii 1.1有所提高。 几年前,当我开始使用Yii 1.1时,我很难弄清内容,我觉得文档比以前更广泛。
Have you looked at Yii 2.0 already or perhaps even built something with it already? Please tell us what you came across. I would love to know your experiences!
您是否已经看过Yii 2.0,或者甚至已经用它构建了一些东西? 请告诉我们您遇到了什么。 我很想知道您的经历!
yii2 v2.0.15