andrewdanilov / yii2-behaviors
AR模型的多种行为
1.0.31
2024-06-01 07:52 UTC
Requires
- php: >=7.4.0
- andrewdanilov/yii2-ckeditor: ~1.0.1
- andrewdanilov/yii2-helpers: ~1.0.17
- andrewdanilov/yii2-input-images: ~1.0.4
- mihaildev/yii2-elfinder: *@dev
- yiisoft/yii2: ^2.0.0
README
AR模型的多种行为
安装
安装此扩展的首选方法是通过 composer。
运行
composer require andrewdanilov/yii2-behaviors "~1.0.0"
或者在您的 composer.json
文件的 require
部分添加
"andrewdanilov/yii2-behaviors": "~1.0.0"
to the require
section of your composer.json
file.
使用
DateBehavior
在控制器类中,将以下代码添加到 behaviors()
方法中
use yii\db\ActiveRecord; use andrewdanilov\behaviors\DateBehavior; class MyController extends ActiveRecord { public function behaviors() { return [ // ... [ 'class' => DateBehavior::class, // AR model attributes to process by behavior 'dateAttributes' => [ // DateTime format 'date_1' => DateBehavior::DATETIME_FORMAT, // DateTime format with current datetime as default value if param is empty 'date_2' => DateBehavior::DATETIME_FORMAT_AUTO, // Date format without time 'date_3' => DateBehavior::DATE_FORMAT, // Date format without time with current datetime as default value if param is empty 'date_4' => DateBehavior::DATE_FORMAT_AUTO, // Short notation equal to: 'date_5' => DateBehavior::DATE_FORMAT 'date_5', ], ], // ... ]; } }
DateBehavior 将在数据保存到数据库之前将日期转换为 mysql 格式(onBeforeSave
事件)以及在从数据库中检索后转换为显示格式(onAfterFind
事件)。
您可以通过修改您的配置中的 Yii::$app->formatter
组件来定义显示格式
$config = [ // ... 'components' => [ // ... 'formatter' => [ 'defaultTimeZone' => 'Europe/Moscow', 'dateFormat' => 'php:d.m.Y', 'datetimeFormat' => 'php:d.m.Y H:i:s', 'timeFormat' => 'php:H:i:s', ], ], ];
如果您遇到时区转换问题,请设置 formatter 的 defaultTimeZone
属性。
TagBehavior
使用此行为通过中间表将两个模型以多对多关系关联起来。此行为将负责保存新链接到中间表并删除过时的链接。
模型 Product.php
<?php namespace common\models; /** * Class Product * * @property int $id * ... * @property int[] $category_ids */ class Product extends \yii\db\ActiveRecord { public $category_ids; public function behaviors() { return [ 'category' => [ // name of behavior 'class' => 'andrewdanilov\behaviors\TagBehavior', 'referenceModelClass' => 'common\models\ProductCategory', 'referenceModelAttribute' => 'product_id', 'referenceModelTagAttribute' => 'category_id', 'tagModelClass' => 'common\models\Category', 'ownerModelIdsAttribute' => 'category_ids', ] ]; } /** * Getter for retrieving child models (tags) list. * It can be used therefore as property $product->categories * or link named 'categories', i.e. $product->with('categories') * * @return \yii\db\ActiveQuery */ public function getCategories() { $behavior = $this->getBehavior('category'); // use name of behavior here ('category') if ($behavior instanceof \andrewdanilov\behaviors\TagBehavior) { return $behavior->getTags(); } return null; } // ... }
模型 Category.php
<?php namespace common\models; use yii\db\ActiveRecord; /** * Class Category * * @property int $id * @property string $name * ... */ class Category extends ActiveRecord { // ... }
模型 ProductCategory.php
<?php namespace common\models; use yii\db\ActiveRecord; /** * Class ProductCategory * * @property int $id * @property int $product_id * @property int $category_id */ class ProductCategory extends ActiveRecord { // ... }
视图 product/update.php
<?php use andrewdanilov\behaviors\TagBehavior; use common\models\Category; use common\models\Product; use yii\helpers\Html; use yii\bootstrap\ActiveForm; /* @var $this yii\web\View */ /* @var $form yii\widgets\ActiveForm */ /* @var $model Product|TagBehavior */ ?> <?php $form = ActiveForm::begin(); ?> ... <?= $form->field($model, 'category_ids')->checkboxList(Category::find()->select(['name', 'id'])->indexBy('id')->column(), ['prompt' => '']) ?> ... <div class="form-group"> <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?> </div> <?php ActiveForm::end(); ?>
TagBehavior 可在一个模型中使用多次,因此您可以将类别、标签和关联产品同时添加到您的 Product
模型中
JsonTypecastBehavior
使用此行为将数据库字段以 json 字符串格式保存的值转换为数组并返回。这允许您将值作为 json 字符串存储在数据库中,但将其作为数组处理。
use andrewdanilov\behaviors\JsonTypecastBehavior; class Item extends \yii\db\ActiveRecord { public function behaviors() { return [ 'jsontypecast' => [ 'class' => JsonTypecastBehavior::class, 'attributes' => [ 'json_field_1', // field names 'json_field_2', 'json_field_3', // ... ], ], ]; } // ... } // Use example: $item = new Item(); $item->json_field_1 = [1, 2, 3]; // before saving json_field_1 will be converted to a json string $item->save(); // then after saving it will be converted back to an array print_r($item->json_field_1); // Outputs: // Array // ( // [0] => 1 // [1] => 2 // [2] => 3 // )
RateLimitBehavior
使用此行为限制访客对特定控制器操作请求的速率。
<?php class MyController extends \yii\web\Controller { public function behaviors(): array { return array_merge(parent::behaviors(), [ 'rateLimit' => [ 'class' => \andrewdanilov\behaviors\RateLimitBehavior::class, // identityKey - key to identify current visitor, optional 'identityKey' => Yii::$app->user->id ?? Yii::$app->session->getId(), 'limits' => [ // '<action>' => [<interval>, <rate>] // <action> - идентификатор действия // <interval> - интервал, на котором проводим измерения // <rate> - доступное число запросов на указанном интервале 'index' => [1, 100], // 100 раз в секунду 'view' => 10, // 10 раз в секунду (сокращенная запись) 'create' => [60, 1], // 1 раз в минуту 'update' => [1, 1], // 1 раз в секунду ], ], ]); } }