Yii 2.0. Release date

    After three years of intensive development and almost 10,000 commits by more than 300 authors , a stable version of the Yii 2.0 PHP framework has been released! Thank you for your support and patience!

    As you may already know, Yii 2.0 has been rewritten from scratch. This decision was made, because we wanted to get an excellent PHP framework that will preserve the simplicity and extensibility of Yii and, at the same time, will use the latest technologies and features to become even better. Today we are pleased to announce that the goal has been achieved.

    Some useful links about Yii and Yii 2.0:



    Next, we will consider the most interesting features of the new version. If you are in a hurry to try the framework in action, start by reading the Getting Started section of the manual .



    The most interesting



    Following standards and using the latest technology


    Yii 2.0 uses PHP namespaces and traits, PSR , Composer, and Bower standards . All this makes working with the framework more enjoyable. Third-party libraries are now much easier to use.

    Solid foundation


    As in 1.1, Yii 2.0 supports object properties through getters and setters, configurations , events, and behaviors . The new code is more efficient and expressive. For example, you can handle the event as follows:

    $response = new yii\web\Response;
    $response->on('beforeSend', function ($event) {
        // обрабатываем событие "beforeSend"
    });
    


    Yii 2.0 implements dependency injection container and service locator . When used correctly, they make applications more flexible and testable.

    Development tools


    Yii 2.0 includes several tools that make life easier for developers.

    The Yii debugger lets you learn the details of your application. It can also be used to profile performance and find bottlenecks.

    As in version 1.1, Yii 2.0 has a significantly time-saving Gii code generator . It expands perfectly, which allows you to create your own generators. You can work with Gii both from the browser and from the console.

    The Yii 1.1 API documentation has received a lot of praise. Many wanted the same documentation for their projects, so a documentation generator was included in Yii 2.0 . It supports Markdown, which allows you to write more concisely and expressively.

    Security


    Yii 2.0 helps you write more secure code. The framework has the capabilities to prevent SQL injection, XSS attacks, CSRF attacks, cookie fakes, etc. Some parts of the code were checked by security experts Tom Worster and Anthony Ferrara and subsequently rewritten.

    Database


    Working with databases has never been so easy. Yii 2.0 supports migrations , DAO , query builder, and Active Record . Compared to 1.1, version 2.0 improves the performance of Active Record, and the syntax for working with it is the same as when working with the query builder. The following shows getting client data using the query builder and Active Record. In both cases, a method call chain that resembles SQL is used.

    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 following code shows samples of related data through Active Record:

    namespace app\models;
    use app\models\Order;
    use yii\db\ActiveRecord;
    class Customer extends ActiveRecord
    {
        public static function tableName()
        {
            return 'customer';
        }
        // задаёт связь типа one-to-many с моделью Order
        public function getOrders()
        {
            return $this->hasMany(Order::className(), ['customer_id' => 'id']);
        }
    }
    // возвращает клиента с id равным 100
    $customer = Customer::findOne(100);
    // возвращает заказы клиента
    $orders = $customer->orders;
    


    Below we update the customer record. Parameter binding is used, which virtually eliminates the possibility of SQL injection. Only modified data is saved to the database.

    $customer = Customer::findOne(100);
    $customer->address = '123 Anderson St';
    $customer->save();  // выполнит SQL: UPDATE `customer` SET `address`='123 Anderson St' WHERE `id`=100
    


    Yii 2.0 supports many databases. In addition to the traditionally used relational databases, support for Cubrid, ElasticSearch, and Sphinx has been added. NoSQL repositories such as Redis and MongoDB are also supported. To access all these databases, both through the query builder and through Active Record, the same API is used, which makes it easy to switch from using one repository to using another. When using Active Record, you can build relationships between data from different databases (for example, between MySQL and Redis).

    For applications with large databases and high performance requirements, Yii 2.0 supports database replication and read / write separation .

    RESTful API


    Yii allows you to get a working and compatible with the latest RESTful API protocols by writing just a couple of lines of code. The example below shows creating a RESTful API for user data.

    First, create a controller app\controllers\UserControllerand specify app\models\Useras a data model:

    namespace app\controllers;
    use yii\rest\ActiveController;
    class UserController extends ActiveController
    {
        public $modelClass = 'app\models\User';
    }
    


    Next, change the configuration of the component urlManagerto use beautiful URLs:

    'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => false,
        'rules' => [
            ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
        ],
    ]
    


    Done! The API that was just created supports:

    • GET /users: a list of all users paginated;
    • HEAD /users: headers with information about the list of users;
    • POST /users: creates a new user;
    • GET /users/123: user information with id = 123;
    • HEAD /users/123: headers with user information with id = 123;
    • PATCH /users/123and PUT /users/123: updates user information with id = 123;
    • DELETE /users/123: removes the user with id = 123;
    • OPTIONS /users: returns supported HTTP verbs for /users;
    • OPTIONS /users/123: returns supported HTTP verbs for /users/123.


    You can try the API with curl:

    $ 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: ; rel=self, 
          ; rel=next, 
          ; rel=last
    Transfer-Encoding: chunked
    Content-Type: application/json; charset=UTF-8
    [
        {
            "id": 1,
            ...
        },
        {
            "id": 2,
            ...
        },
        ...
    ]
    


    Caching


    As in version 1.1, Yii 2.0 has excellent support for caching both on the server side ( fragments , requests ) and on the client side ( HTTP ). There are drivers for many storages, including APC, Memcache, files, databases, etc.

    Forms


    In Yii 1.1, you can quickly create HTML forms that support both client and server validation. In the second version, it is even easier to do . The example below shows the creation of a login form.

    First, a model is created LoginFormthat represents the data collected from the form. The model specifies validation rules that will be automatically used to generate the JavaScript necessary for validation on the client.

    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.');
            }
        }
    }
    


    Next, create a view:

    use yii\helpers\Html;
    use yii\widgets\ActiveForm;
    
        field($model, 'username') ?>
        field($model, 'password')->passwordInput() ?>
        
    
    


    Authentication and Authorization


    As in version 1.1, Yii 2.0 has a built-in ability to authenticate and authorize the user. Sign-in, sign-out, cookie and token authentication , access control filter and role-based access control (RBAC) are supported .

    It is also possible to log in through external services using OpenID, OAuth1 and OAuth2. There is also ready-made support for popular services such as Facebook, GitHub, Google, Twitter, Vkontakte and Yandex.

    Widgets


    To build interactive user interfaces, the framework includes quite a few ready-made elements called widgets . There is support for Bootstrap and jQuery UI widgets . In addition, commonly used items such as pagination, grid, list, etc. are provided. All of them make web application development a really quick and enjoyable process. For example, using the following code, you can get a fully working jQuery UI element to select a date in Russian:

    use yii\jui\DatePicker;
    echo DatePicker::widget([
        'name' => 'date',
        'language' => 'ru',
        'dateFormat' => 'yyyy-MM-dd',
    ]);
    


    Helpers


    To simplify common tasks, the framework has helpers . For example, the helper Htmlcontains methods for creating various HTML tags, and the helper Urlallows you to create different URLs:

    use yii\helpers\Html;
    use yii\helpers\Url;
    // создаёт список чекбоксов со странами
    echo Html::checkboxList('country', 'USA', $countries);
    // выводит URL "/index?r=site/index&src=ref1#name"
    echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name']);
    


    Internationalization


    Since the framework is used all over the world, we have taken care of good support for internationalization. Supported translation of messages and translation of view , locale-based multiple forms and data formatting according to the ICU standard . For instance:

    // переводим сообщение с форматированием даты
    echo \Yii::t('app', 'Today is {0, date}', time());
    // переводим сообщение с множественными формами
    echo \Yii::t('app', 'There {n, plural, =0{are no cats} =1{is one cat} other{are # cats}}!', ['n' => 0]);
    



    Template engines


    By default, Yii 2.0 uses PHP as the template language, but also supports Twig and Smarty through special extensions . It is possible to create your own extensions to support other template engines.

    Testing


    Yii 2.0 officially supports integration with Codeception and Faker . The framework includes a solution for fixtures via migrations, which makes working with test data more convenient.

    Application Templates


    In order to make development even faster, the release includes two application templates, each of which is a fully operational web application. The basic template is recommended as a basis for small, relatively simple web projects, such as portals and personal sites. The advanced template is more suitable for large applications with the division into many servers developed by a large team.

    Extensions


    Despite the fact that Yii 2.0 provides many useful features, it has an extension system that makes it even more powerful. Extensions are separately distributed packages specifically designed for use in Yii applications. Many of Yii’s features are already in extensions, such as mail sending and Bootstrap . Yii has a large user library , which currently has nearly 1,700 extensions. More than 1300 packages for Yii can be found on packagist.org .

    Beginning of work



    To get started, enter the following commands:

    # устанавливаем composer-asset-plugin глобально. Это нужно сделать один раз.
    php composer.phar global require "fxp/composer-asset-plugin:1.0.0-beta2"
    # устанавливаем шаблон приложения basic
    php composer.phar create-project yiisoft/yii2-app-basic basic 2.0.0
    


    The commands above will work if you already have Composer installed . If this is not the case, it is worth installing it .

    It is worth noting that during the installation process Composer may require a login and password from GitHub to generate a token, which allows you to overcome the restrictions on the number of API requests.

    After executing the commands above, you can start working with a web application accessible by URL localhost/basic/web/index.php.

    Updated



    If you are upgrading from previous versions of Yii 2.0 (alpha, beta, or RC), follow the instructions .

    Upgrading from version 1.1 without rewriting the application code is not possible since Yii 2.0 has been completely rewritten and there are a lot of syntax changes. Nevertheless, many ideas have been saved, so working with 2.0, knowing 1.1, will be easier. Big changes compared to version 1.1 are described in detail in the documentation .

    Documentation



    A complete guide and API documentation is available for Yii 2.0 . The manual is translated into many languages . Translations will be available a little later. According to Yii 2.0 , one book has already been released and more are being written. One of the books will be written by renowned technical writer Larry Ullman , who helps us with a complete guide. Alexander Makarov coordinates and edits the Yii 2.0 recipe book , similar to the warmly received Yii 1.1 recipe book.

    thanks



    Thanks to everyone who took part in the development of Yii .
    Your support is invaluable!

    Also popular now: