M
M
Maxim2018-09-04 01:18:17
Yii
Maxim, 2018-09-04 01:18:17

Yii how best to assign ratings to a user?

Hello! Quite a simple task, but I just can’t decide how to do it right in Yii. You need to add user ratings on the site.
I chose the following structure:

public function attributeLabels()
    {
        return [
            'id' => Yii::t('rating', 'ID'),  //id рейтинга
            'user_id' => Yii::t('rating', 'User ID'), //id пользователя
            'value' => Yii::t('rating', 'Value'), //присваиваемое значение рейтинга (положительное/отрицательное)
            'type_id' => Yii::t('rating', 'Type ID'), //Тип рейтинга (комментарии, ответы...)
            'record_id' => Yii::t('rating', 'Record ID'), //id записи в системе для возможности отката
            'created_at' => Yii::t('rating', 'Created At') //Дата создания рейтинга
        ];
    }

The final rating will be obtained by request, which will be cached, or I will create it in a table
user
new field
rating
and there I will store the final rating. It would not be bad to comment on this point as well.
I'm going to use it as follows:
The user performs some action, for example, leaves a comment, registers, fills out a profile, publishes material ... For this, he is entitled to a reward, which is fixed in the table
rating
.
In this regard, I had questions: Where should I write the code? How to assign a rating to a user? What to use: events or behaviors, components or models? In other words, how to put the right code in the right place.
For example, we write to the database in the Rating model. To initiate the recording, we use behaviors + events. We prescribe calculations in the component ....
I hope I correctly stated my question. If something is not clear - write in the comments. Such questions are most likely due to partial knowledge of the framework. What are components, behaviors, events and so on used for..))
Right now there is the following code in the Rating model
/**
     * Список типов рейтинга
     * @return array
     */
    public function getTypeList()
    {
        return [
            [ 'id' => 1, 'value' => 3, 'description' => 'Лайк'],
            [ 'id' => 2, 'value' => 5, 'description' => 'Комментарий'],
            [ 'id' => 3, 'value' => 30, 'description' => 'Заполнение профиля'],
            [ 'id' => 4, 'value' => 10, 'description' => 'Регистрация на сайте'],
        ];
    }

    /**
     * Добавление рейтинга пользователю
     * по переданным параметрам
     * @param int $user_id
     * @param int $type_id
     * @param int $record_id
     */
    public function getAddUserRating(int $user_id, int $type_id, int $record_id = null)
    {
        $model = new self();
        $value = 3;
        $model->user_id = $user_id;
        $model->value = $value;
        $model->type_id = $type_id;
        $model->record_id = $record_id;
        $model->created_at = time();
        $model->save();
    }

    /**
     * Удаление рейтинга пользователя
     * по id записи (откат)
     * @param $record_id
     */
    public function getDeletedUserRatingByRecord(int $record_id)
    {
        self::deleteAll(['record_id' => $record_id]);
    }

    /**
     * Изменение рейтинга пользовании по id записи
     * @param int $record_id
     * @return string
     */
    public function getUpdatedUserRatingByRecord(int $record_id)
    {
        //Код изменение рейтинга;
    }

    /**
     * Полное удаление всего рейтинга пользователя
     * по id пользователя
     * @param int $user_id
     */
    public function getDeletedUserRatingByUserId(int $user_id)
    {
        self::deleteAll(['user_id' => $user_id]);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey K, 2018-09-04
@myks92

Conducting (Behavior) is needed in order to use a repeating piece of code in different places without copying it every time. For example, saving photos may be necessary for the profile picture and for the cover of an article.
Events are needed in order to be able to react to it in different places of the code. For example, if we have a new like for a user, we add a rating for this case, and in another place we can check that the rating has reached a certain level and we need to change the signature, in the third place we send him a letter of congratulations on the new rating. Events allow you to do all this without being strongly dependent on each other.
Components are usually some things that are needed in different parts of the application, and often in a single instance, for example, we want to put the model in as narrow a place as possible, so it is not a component (although, in my opinion, it is also inherited from it, but I’m not sure) ... I didn’t even think of something right away, why in your case you might need your own component, with the exception of the framework infrastructure, such as Request, Response, Routing, Sessions, etc.
As a result:
The controller receives the request and forwards it to the model layer, the model does something and the controller renders the view (view) and sends the result.
The model, if there is no special logic, then it can be Active Record itself, if there is a lot of logic, services are created, this is also a layer of the model, but this way the code is clearer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question