The much-awaited Yii PHP framework 2.0 is finally on its way to the deck. Kudos to your patience and support, after carrying out intensive research and development, for about three years or more with around 10,000 commits and by more than 300 authors.
You might be well aware of the fact that the new version, ‘Yii 2.0’ is more or less a rewrite of its older version, ‘Yii 1.1’. The main idea behind this is – building up an avant-garde PHP framework by maintaining the authenticity, extensibility as well as the simplicity of the previous version while leveraging the benefits of the latest features and technologies to make the entire thing perform better. Well, the years have speculations have ended with the newly developed and advanced PHP frameworks.
Here are some useful links are given below. To know more about Yii and Yii 2.0, you can go through them:
- Yii 2.0 GitHub Project ( If you want you can bookmark the same to track future development activities)
- Yii Twitter feeds
- Yii Facebook group
- YiiLinkedin group
- Yii project site
In this article you will come to know about some of the main highlights of Yii 2.0 framework. In case, you don’t want to wait any more to discover this long awaited framework, then Getting started is the best option for you.
(adsbygoogle = window.adsbygoogle || []).push({});
Here comes the highlight of this amazing PHP framework:
Use of latest technologies with impeccable standards
The all new Yii 2.0 has made use of PHP traits as well as namespaces along with Bower, Composer and PHP Specification Request (PSR) Standards. All these elements together make Yii 2.0 an amazingly refreshing. The best part, it can inter-operate with other libraries as well.
Robust PHP foundation classes
Just like its former counterpart, Yii 2.0 framework also supports object properties that are defined through getter and setters method, events, behaviours and configurations. Moreover, the latest version is more expressive and systematic than the previous one. Here is an example that will help you write the code given below when it comes to responding to an event.
$response = new yii\web\Response; $response->on('beforeSend', function ($event) { // respond to the "beforeSend" event here });
Yii 2.0 executes dependency injection container. It also implements service locater. All these features enhance the testability of application that is built on Yii framework. Also, the entire thing becomes more customizable.
Improved development tools
With this new framework the developers can take a sigh of great relief, as it comes with a number of development tools. Let’s take a quick look at them: Now you can easily test the runtime internals of the applications with the help of Yii debugger. Moreover, performance profiling is also made easy with the same. The former will help you figure out the performance bottlenecks in regard to the application.
As said above, Yii 2.0 is an improved version of Yii1.1; it does not lack your very own code generator tool, Gii. It can save a lot of development time. Gii is really very efficient and extendable. It allows you to create as well as custom tailor different types of code generators. You can use Gii on UIs (User Interfaces), console and web. User preference is not at all compromised.
One of the main features of Yii 1.1 is the API documentation. There are a number of users who wanted to develop more or less similar documentation features. In Yii 2.0 this wish is fulfilled with the introduction of documentation generator. As the latter supports Markdown syntax, users can develop expressive and concise documentation.
Improved security
With Yii 2.0, writing secure (much more than before)codes has also become easy. You can easily prevent cookie tampering, SQL injections, CSRF attacks, XSS attacks and other threats with the help of Yii 2.0’s built-in support. When top notch security experts like Anthony Ferrara and Tom Worsterhave assisted with the rewrite and review of some of the codes, obviously security related.
Improved database
The latest counterpart of Yii 1.1 supports query builder, active record, DAO (database access objects) and DB migration. Needless to say, these make working with the databases extremely easy and simple. In comparison to the former version, the latter one helps in the improvement of active record’s performance. It also unites syntax for the purpose of querying data through active record and query builder. Here is an example given below that will help you know how customer data can be queried by using either of the two – active record or query builders. As it’s quite clear from the code that both the techniques utilized the method chaining (chained method calls). They are more like SQL syntax. Here is the code –
use yii\db\Query; use app\models\Customer; $customers = (new Query)->from('customer') ->where(['status' => Customer::STATUS_ACTIVE]) ->orderBy('id') ->all(); $customers = Customer::find() ->where(['status' => Customer::STATUS_ACTIVE]) ->orderBy('id') ->asArray(); ->all();
The code given below shows how relational queries can be performed using Active Record:
namespace app\models; use app\models\Order; use yii\db\ActiveRecord; class Customer extends ActiveRecord { public static function tableName() { return 'customer'; } // defines a one-to-many relation with Order model public function getOrders() { return $this->hasMany(Order::className(), ['customer_id' => 'id']); } } // returns the customer whose id is 100 $customer = Customer::findOne(100); // returns the orders for the customer $orders = $customer->orders;
Here is another code that shows how a customer data can be updated. In order to prevent attacks like that of SQL injection, parameter binding has been used (hidden). Also, just the modified columns are saved on the database.
$customer = Customer::findOne(100); $customer->address = '123 Anderson St'; $customer->save(); // executes SQL: UPDATE `customer` SET `address`='123 Anderson St' WHERE `id`=100
One of the best parts of Yii 2.0 is – it supports a number of different types of databases. Apart from the conventional databases, this new version supports many new ones, like Sphinx, Cubrid and ElasticSearch. NoSQL databases, like MongoDB and Redis are also on the list. The most important part – the same Active Record APIs and query builder can be used for them. This makes working on this platform easy. Most important, whenever needed you can switch between the databases. As far as when using Active Record is concerned, you can relate data belonging to different databases.
Read-write splitting as well as database replicationis two of the other features that Yii 2.0 provides support (built-in) for. These are particularly efficient for applications that require high performance and have huge databases.
RESTful APIs
Now with the help of Yii 2.0 it has become quite easy to develop a complete set of RESTful APIs (fully functional) compatible with the recent protocols. All you need is just a couple of codes. Here is an example given below. It will help you understand that how a RESTful API can be created serving the user data:
Firstly, you have to develop a controller class app\controllers\UserController and you have to mention app\models\User.
namespace app\controllers; use yii\rest\ActiveController; class UserController extends ActiveController { public $modelClass = 'app\models\User'; }
Secondly, in order to serve the user data into pretty URLs, modification in the configuration about your urlManager component in the application configuration is needed.
'urlManager' => [ 'enablePrettyUrl' => true, 'enableStrictParsing' => true, 'showScriptName' => false, 'rules' => [ ['class' => 'yii\rest\UrlRule', 'controller' => 'user'], ], ]
It’s all that is needed. This API supports the following:
- GET /users: list all users page by page;
- HEAD /users: show the overview information of user listing;
- POST /users: create a new user;
- GET /users/123: return the details of the user 123;
- HEAD /users/123: show the overview information of user 123;
- PATCH /users/123 and PUT /users/123: update the user 123;
- DELETE /users/123: delete the user 123;
- OPTIONS /users: show the supported verbs regarding endpoint /users;
- OPTIONS /users/123: show the supported verbs regarding endpoint /users/123.
You can also access your API using a curl command. Take a look –
$ curl -i -H "Accept:application/json" "http://localhost/users" HTTP/1.1 200 OK Date: Sun, 02 Mar 2014 05:31:43 GMT Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y X-Powered-By: PHP/5.4.20 X-Pagination-Total-Count: 1000 X-Pagination-Page-Count: 50 X-Pagination-Current-Page: 1 X-Pagination-Per-Page: 20 Link: <http://localhost/users?page=1>; rel=self, <http://localhost/users?page=2>; rel=next, <http://localhost/users?page=50>; rel=last Transfer-Encoding: chunked Content-Type: application/json; charset=UTF-8 [ { "id": 1, ... }, { "id": 2, ... }, ... ]
The caching options
Yii 2.0 also supports the caching options supported by the previous versions. Some of the server side caching include – query caching and fragment caching, whereas the client side option includes HTTP caching. These are supported on a number of caching drivers, like Memcache, databases, files, APC and many more.
The Forms
You might know that it is quite easy to create forms (HTML) in Yii 1.1. It supports both types of validation – server and client side. However, with Yii 2.0 it is way for easy to create forms. Here is an example in which a login form is created using the same.
First of all, create a model of the login form. In this, you will have to make a list of rules that you need to use for validating the user input. This will be used for generating the required thing automatically. In this case it’s JavaScript Validation Logic (client side.) In this way working with forms has become easy
use yii\base\Model; class LoginForm extends Model { public $username; public $password; /** * @return array the validation rules. */ public function rules() { return [ // username and password are both required [['username', 'password'], 'required'], // password is validated by validatePassword() ['password', 'validatePassword'], ]; } /** * Validates the password. * This method serves as the inline validation for password. */ public function validatePassword() { $user = User::findByUsername($this->username); if (!$user || !$user->validatePassword($this->password)) { $this->addError('password', 'Incorrect username or password.'); } } }
Then create the view code for the login form:
use yii\helpers\Html; use yii\widgets\ActiveForm; <?php $form = ActiveForm::begin() <?= $form->field($model, 'username') <?= $form->field($model, 'password')->passwordInput() <?= Html::submitButton('Login') <? ActiveForm::end()
(adsbygoogle = window.adsbygoogle || []).push({});
Authorization and authentication
For user authorization and authentication, Yii 2.0 also offers built-in support, like its previous version. Token-based, cookie-based, login, logout, support to all such features is provided. (RBAC) Role-based access control as well as access control filter are also included in the list.
More widgets
With Yii 2.0, you can make use of widgets. They are sets of UI elements. It will help you create interactive UIs in no time. It also provides support for jquery UI and Bootstrap widgets. Some of the most common and popular widgets provided by the same are list view, grid view, pagers, detail and others. All these things together make web app development extremely easy, speedy and enjoyable. Here is an example for you. With the coding given below you will be able to create a date picker (jQuery) in Russian:
use yii\jui\DatePicker; echo DatePicker::widget([ 'name' => 'date', 'language' => 'ru', 'dateFormat' => 'yyyy-MM-dd', ]);
More helpers
By using Yii 2.0 framework you will be able to simplify some of the most frequently done tasks as it provides a number of effectual helper classes. Here is an example – the HTML helper comprises a complete set of methods for creating different types of HTML tags, whereas, the URL helper allows you to create different URLs. Here is how –
use yii\helpers\Html; use yii\helpers\Url; // creates a checkbox list of countries echo Html::checkboxList('country', 'USA', $countries); // generates a URL like "/index?r=site/index&src=ref1#name" echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name']);
Internationalization –
Yii supports internationalization. The reason – it is a worldwide framework. Some of the features it supports, in regard to its worldwide use are – view translation and message translation. Besides, it also supports data formatting and plural forms (locale-based) that are compatible with the ICU standard. Here is an example –
// message translation with date formatting echo \Yii::t('app', 'Today is {0, date}', time()); // message translation with plural forms echo \Yii::t('app', 'There {n, plural, =0{are no cats} =1{is one cat} other{are # cats}}!', ['n' => 0]);
Template engines
PHP is the default template language for Yii 2.0. It also provides support for Smarty and Twig via the template engine extensions. One of the best features – it allows you to build extensions for supporting others as well.
Testing
Faker and Codeception are two of the most important components that helpYii 2.0 to strengthen the support for testing.
Application templates
The Yii is launched along with two different application templates. Each of which is a web application (fully functional). You can make use of the basic application template to initiate simple and small website development. For huge business enterprise application the advanced application template is a better option.
Extensions –
With all the newly developed features, Yii 2.0 turns out to be a self-sufficient platform, but the extension architecture makes it more powerful. The latter are different types of redistributable computer application packages that are specially designed for Yii applications. They also offer various ready to use options. Some of the built-in options in this regards are – Bootstrap and mailing. It also has an extension library that is user-contributed. It is supposed to include more than 1700 extensions. Furthermore, the number of Yii related stuff on packagist.org is also over 1300.
Getting started
In order to be with Yii 2.0, just run the commands given below:
# installs the composer-asset-plugin globally. This needs to be run only once.
phpcomposer.phar global require “fxp/composer-asset-plugin:1.0.0-beta3”
# install the basic application template
phpcomposer.phar create-project yiisoft/yii2-app-basic basic 2.0.0
Do you have a composer? In case you don’t have this, then you have to install it. You can do it by following Composer installation instructions. You might be asked to put your user id and password (GitHub) while installing the composer. With the help of above-mentioned commands, you will have you are ready to use the web app.
Upgrading
If you want to upgrade from the older Yii 2.0 releases, like 2.0.0-rc or 2.0.0-beta, you have to follow proper upgrade instructions. If you want to upgrade from Yii 1.1, it might not be an easy task for you. That’s because the latest versions are the complete rewrites of the previous with a number of syntax changes. In order to learn about the major alterations included in Yii 2.0, please go through the upgrade instructions.
Documentation –
Yii 2.0 has got its class reference as well definitive guide. The latter can be translated to many languages. You will also find some book on Yii 2.0. These are books are just published and are by some of the most popular authors, like Larry Ullman. Also, Alexander Makarov is the coordinator of community-contributed repository, cookbook about Yii 2.0.
Link Source: http://goo.gl/1L0Rfq