Tag: yii

  • Saving “many-to-many” in Yii2 through behavior

    CleanTalk is a SaaS spam protection service for Web-sites. CleanTalk uses protection methods which are invisible for site visitors. Connecting to the service eliminates needs for CAPTCHA, questions and answers and other methods of protection, complicating the exchange of information on the site.

    bbc47933552e4c90846c80e731b06ddfIf you had to work with Yii2 sure there was a situation when it was necessary to keep communication “many-to-many”.

    When it became clear that the network has no behaviors to work with this type of connection, then the correct code was written at the event «after save» and with a warning “works well also” went to the repository.

    Personally, I am not satisfied with such a disposition of events. I decided to write something very magical behavior, which is so lacking in the official assembly Yii2.

    Installation

    Install through the Composer:

    php composer.phar require --prefer-dist voskobovich/yii2-many-many-behavior "*"
    

    Or add into composer.json of your project to the section «require»:

    "voskobovich/yii2-many-many-behavior": "*"
    

    Execute:

    ~$ php composer.phar update
    

    Source: yii2-many-many-behavior.

    How to use?

    Connecting the behavior in the desired model ActiveRecord:

    public function behaviors()
    {
        return [
            [
                'class' => \voskobovich\behaviors\ManyToManyBehavior::className(),
                'users_list' => 'users',
                'tasks_list' => [
                    'tasks',
                    'get' => function($value) {
                        return JSON::decode($value);
                    },
                    'set' => function($value) {
                        return JSON::encode($value);
                    },
                 ]
            ],
        ];
    }
    

    This example describes two connections:

    1. Communication «users» will receive and store the primary keys in the properties of the model «users_list».
    2. Communication «tasks» respectively «tasks_list». At the same time, for a given connection are indicated handlers «set» and «get» which process data before saving the communication and output in the field.

    Please note that the properties of «users_list» and «tasks_list» will appear in the model automatically!

    Next, add fields in the form of creating/edit:

    <?= $form->field($model, 'users_list')
          ->dropDownList(ArrayHelper::map(User::find()->all(), 's_id', 'name'), ['multiple' => true]) ?>
    

    and allow them to update through mass assignment by adding validation rules:

    public function rules()
    {
        return [
            [['users_list', 'tasks_list'], 'safe']
        ];
    }
    

    or you can work with new properties directly:

    $model->users_list = [2,5,6,7];
    

    After these manipulations links will be updated automatically.

    From the properties of «users_list» and «tasks_list» you can also get an array of primary keys stored on communication models.

    print_r($model->users_list);
    

    Returns an array of primary keys stored on the communication «users».

    It is worth saying that the formation of a list of primary keys happens only at the moment of the call of reading properties.

    Thank you for your attention!

    This text is a translation of the article “Сохранение “много ко многим” в Yii2 через поведение” by rafic published on habrahabr.ru.

    Forums and blogs without spam

    CleanTalk is a SaaS spam protection service for Web-sites. CleanTalk uses protection methods which are invisible for site visitors. Connecting to the service eliminates needs for CAPTCHA, questions and answers and other methods of protection, complicating the exchange of information on the site.

  • Yii 2.0. Release

    CleanTalk is a SaaS spam protection service for Web-sites. CleanTalk uses protection methods which are invisible for site visitors. Connecting to the service eliminates needs for CAPTCHA, questions and answers and other methods of protection, complicating the exchange of information on the site.

    After three years of intensive development and nearly 10,000 commits more than 300 authors published a stable version of PHP framework Yii 2.0! 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 a good PHP framework that preserves the simplicity and extensibility of Yii and, at the same time, will use the latest technologies and capabilities to become even better. Today we are pleased to announce that the goal has been reached.

    A few useful links about Yii and Yii 2.0:

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

    The most interesting

    Adherence to the standards and use the latest technologies

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

    Reliable basis

    As 1.1, Yii 2.0 supported 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) {
        // handle the event "beforeSend"
    });
    

    In Yii 2.0 are realized dependency injection container and service locator. When used properly, they make applications more flexible and testable.

    Development tools

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

    Yii debugger allows to study the details of your application. It can also be used for profiling and find bottlenecks.

    As of version 1.1, Yii 2.0 have significantly saving time code generator Gii. It perfectly expands that lets you create your generators. Gii can work with both the browser and from the console.

    Documentation API Yii 1.1 has received many accolades. Many wanted the same documentation for their projects, so Yii 2.0 included documentation generator. It supports Markdown, which allows you to write more consistently and eloquently.

    Security

    Yii 2.0 helps you write more secure code. In the framework, there are opportunities to prevent SQL injection, XSS attacks, CSRF attacks, forgery cookie etc. Some parts of the code have been checked by security experts Tom Worster and Anthony Ferrara and later rewritten.

    Databases

    Working with databases has never been this easy. Yii 2.0 supports migration, DAO, query builder and Active Record. When compared to 1.1 in version 2.0 improved performance of Active Record, and the syntax to work with this is the same as when using the Query Builder. Below shows the preparation of customer data using the Query Builder and Active Record. In both cases use the chain of method invocation, which resembles SQL.

    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 a sample 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';
        }
        
        // specifies the type of connection one-to-many with model Order
        public function getOrders()
        {
            return $this->hasMany(Order::className(), ['customer_id' => 'id']);
        }
    }
    
    // returns to the client with id equal to 100
    $customer = Customer::findOne(100);
    // returns the client orders
    $orders = $customer->orders;
    

    Below we update the customer record. This uses the binding parameters, which virtually eliminates the possibility of SQL injection. The database saves only changed data.

    $customer = Customer::findOne(100);
    $customer->address = '123 Anderson St';
    $customer->save();  // execute SQL: UPDATE `customer` SET `address`='123 Anderson St' WHERE `id`=100
    

    Yii 2.0 supports multiple databases. Besides the commonly used relational database support added Cubrid, ElasticSearch and Sphinx. Also supported and NoSQL store such as Redis and MongoDB. To access all the databases, both through the Query Builder, and through Active Record uses the same API, making it easy to migrate from one repository to another use. If you use Active Record can build links between data from different databases (for example, between MySQL and Redis).

    For applications with large databases and high performance requirements in Yii 2.0 supports replication of DB and division read/write.

    RESTful API

    Yii allows you to get a working and compatible with the latest protocols RESTful API to write only a few lines of code. The example below shows the creation of RESTful API for user data.

    First, create a controller app\controllers\UserController and specify app\models\User as 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 urlManager so to use beautiful URL:

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

    Done! API, which was just created, supports:

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

    API, you can try using curl:

    $ curl -i -H "Accept:application/json" "https://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: <https://localhost/users?page=1>; rel=self, 
          <https://localhost/users?page=2>; rel=next, 
          <https://localhost/users?page=50>; 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 cache as excellent support on the server side (fragments, requests) and client side (HTTP). There are many drivers for storage, including APC, Memcache, files, databases, etc.

    Forms

    In Yii 1.1, you can quickly create an HTML form that supports both client and server validation. In the second version make it even easier. The following example shows how to create the login form.

    First created model LoginForm, which is collected from the form data. The model specifies the validation rules which are automatically used to generate the necessary validation on the client JavaScript.

    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;
    
    <?php $form = ActiveForm::begin() ?>
        <?= $form->field($model, 'username') ?>
        <?= $form->field($model, 'password')->passwordInput() ?>
        <?= Html::submitButton('Login') ?>
    <? ActiveForm::end() ?>
    

    Authentication and authorization

    As of version 1.1, Yii 2.0 has built-in authentication and user authorization. Supports input, output, cookie-based authentication and token, access control filter and access control based on roles (RBAC).

    It is also possible entry via external services for OpenID, OAuth1 and OAuth2. There are ready-made support for popular services such as Facebook, GitHub, Google, Twitter, Vkontakte and Yandex.

    Widgets

    For building interactive user interfaces in the framework included a lot of ready-made elements called widgets. There is support for widgets Bootstrap and jQuery UI. It also offers such frequently used items like pagination, grid, list, etc. All they are doing web application development is really fast and pleasant process. For example, using the following code, you can get a fully working element jQuery UI 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 in the framework, there are helpers. For example, in Html helper methods are assembled to create different HTML tags and Url helper allows you to create different URL:

    use yii\helpers\Html;
    use yii\helpers\Url;
    
    // creates a list of checkboxes with countries
    echo Html::checkboxList('country', 'USA', $countries);
    
    // displays the URL "/index?r=site/index&src=ref1#name"
    echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name']);

    Internationalization

    Since the framework is used around the world, we have taken care of a good support for internationalization. Supports message translation and translation of view, based on the locale multiple forms and data formatting standard ICU. For example:

    // translation of message formatted date
    echo \Yii::t('app', 'Today is {0, date}', time());
    
    // translation of message with multiple forms
    echo \Yii::t('app', 'There {n, plural, =0{are no cats} =1{is one cat} other{are # cats}}!', ['n' => 0]);
    
    

    Templating

    By default, Yii 2.0 uses as a template language PHP, but also supports Twig and Smarty through special extensions. Ability to create and expand their support for other template.

    Testing

    Yii 2.0 officially supports integration with Codeception and Faker. The framework included a decision to fixture through the migration, which makes the work with the data for testing more convenient.

    Application templates

    In order to make the development more rapidly in release includes two templates of applications, each of which is a fully functional web application. Basic template is recommended to use as a basis for relatively simple small web projects, such as portals and personal websites. Advanced template is more suitable for large-scale applications divided into a plurality of servers developed by a large team.

    Extensions

    Despite the fact that Yii 2.0 provides many useful features, it implemented a system extension that makes it even more powerful. An extension is distributed separately packages specifically designed for use in applications Yii. Many opportunities already handed in Yii extensions, such as sending mail and Bootstrap. The site has a large Yii user library, currently numbering nearly 1,700 extensions. Packagist.org can be found on more than 1,300 packages for Yii.

    Getting Started

    To get started, enter the following commands:

    # set composer-asset-plugin globally. This should be done once.
    php composer.phar global require "fxp/composer-asset-plugin:1.0.0-beta2"
    
    # set the basic application template
    php composer.phar create-project yiisoft/yii2-app-basic basic 2.0.0
    

    The above commands will work if you have already installed Composer. If it is not, it is necessary to install it.

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

    After executing the above command, you can start working with the web application available at URL https://localhost/basic/web/index.php.

    Update

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

    Upgrading from version 1.1 without rewriting application code is impossible since Yii 2.0 has been completely rewritten and syntax changes a lot. Nevertheless, many ideas are stored, so that work with 2.0, 1.1 knowledge, will be easier. Big changes compared to version 1.1 are described in detail in the documentation.

    Documentation

    For Yii 2.0 is available complete guide and documentation for API. Manual translated into many languages. Translations will be available a little later. By Yii 2.0 is already out one book and write more. One of the books will be written by well-known technical writer Larry Ullman, who helps us with a complete guide. Alexander Makarov coordinates and edits the cookbook Yii 2.0, similar to that adopted by the warm cookbook Yii 1.1.

    Thanks

    Thanks to all who participated and participates in the development Yii.
    Your support is invaluable!

    This text is a translation of article “Yii 2.0. Релиз” by SamDark published on habrahabr.ru.

    Forums and blogs without spam

    CleanTalk is a SaaS spam protection service for Web-sites. CleanTalk uses protection methods which are invisible for site visitors. Connecting to the service eliminates needs for CAPTCHA, questions and answers and other methods of protection, complicating the exchange of information on the site.