Answer the question
In order to leave comments, you need to log in
How to write behaviors in yii2 correctly?
Actually, there are several tasks:
- Add an ip address to the required field
- Add an entry to a separate table when a user logs in (login history)
- Add a record of data changes in the admin panel, admin monitoring.
To solve these cases, I chose behavior.
I read the examples of the article about writing behaviors, but there are points that I did not understand and I want to clarify.
The first and simplest behavior is to write the IP address in the required field:
<?php
namespace common\behaviors;
use Yii;
use yii\db\BaseActiveRecord;
use yii\db\Expression;
use yii\base\Behavior;
/**
* IpBehavior автоматически заполняет указанные атрибуты с текущим ip адресом
*
*
* public function behaviors()
* {
* return [
* 'IpBehavior' => [
* 'class' => IpBehavior::className(),
* 'attributes' => [
* ActiveRecord::EVENT_BEFORE_INSERT => 'ip',
* ActiveRecord::EVENT_BEFORE_UPDATE => 'ip',
* ]
* ],
* ];
* }
* ```
*/
class IpBehavior extends Behavior
{
public $attributes = [
BaseActiveRecord::EVENT_BEFORE_INSERT => 'ip',
BaseActiveRecord::EVENT_BEFORE_UPDATE => 'ip',
];
/**
* Назначаем обработчик для событий
* @return array события (array keys) с назначеными им обработчиками (array values)
*/
public function events()
{
$events = $this->attributes;
foreach ($events as $i => $event) {
$events[$i] = 'getCurrentIp';
}
return $events;
}
/**
* Добавляем IP адрес
* @param Event $event Текущее событие
*/
public function getCurrentIp($event)
{
$attributes = isset($this->attributes[$event->name]) ? (array)$this->attributes[$event->name] : [];
if (!empty($attributes)) {
foreach($attributes as $source => $attribute) {
$this->owner->$attribute = Yii::$app->request->userIP;
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Yes that's right.
only it is probably better to inherit from AttributeBehavior. At the same time, look at how it works and how the standard behaviors inherited from it work, and refactor a little.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question