eseperio/yii2-model-virtual-fields 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

eseperio/yii2-model-virtual-fields

Composer 安装命令:

composer require eseperio/yii2-model-virtual-fields

包简介

Yii2 extension for adding virtual (dynamic) fields to ActiveRecord models without modifying database tables

README 文档

README

A Yii2 extension for adding virtual (dynamic) fields to ActiveRecord models without modifying database tables.

Overview

This library allows developers to define new fields for any ActiveRecord entity at runtime. These virtual fields:

  • Have a name, datatype, and validation rules
  • Are stored in dedicated tables managed by the extension
  • Are exposed on the model as native properties ($model->virtualFieldName)
  • Automatically integrate with:
    • ActiveForm
    • DetailView
    • GridView
    • Model validation
    • Model persistence

Features

  • ✅ Add dynamic fields to existing models without altering database schemas
  • ✅ Support for multiple data types: string, int, float, bool, date, datetime, json, text
  • ✅ Automatic validation based on field type and requirements
  • ✅ Collision-safe field naming (prevents conflicts with existing properties)
  • ✅ Seamless integration with Yii2 widgets (forms, grids, detail views)
  • ✅ Caching support for improved performance
  • ✅ Full test coverage

Installation

Install via Composer:

composer require eseperio/yii2-model-virtual-fields

Configuration

1. Configure the Module

Add the module to your application configuration:

'modules' => [
    'virtualFields' => [
        'class' => 'eseperio\virtualfields\Module',
        'entityMap' => [
            1 => 'app\models\User',
            2 => 'app\models\Product',
            3 => 'app\models\Order',
            // ... more entity type mappings
        ],
    ],
],

The entityMap property maps integer IDs to fully qualified class names of your ActiveRecord models. The extension uses these integer IDs internally to identify entity types.

2. Run Migrations

Apply the database migrations:

php yii migrate --migrationPath=@vendor/eseperio/yii2-model-virtual-fields/migrations

This will create the necessary tables:

  • virtual_field_definition - stores field definitions
  • virtual_field_value - stores field values

3. Attach Behavior to Models

Add the behavior to any ActiveRecord model you want to support virtual fields:

namespace app\models;

use yii\db\ActiveRecord;
use eseperio\virtualfields\behaviors\VirtualFieldsBehavior;

class User extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'virtualFields' => [
                'class' => VirtualFieldsBehavior::class,
            ],
        ];
    }

    /**
     * Return the entity type ID from the module configuration
     */
    public function getObjectType()
    {
        return 1; // Must match the ID in entityMap
    }
}

Usage

Creating Virtual Fields

Create virtual field definitions programmatically or through a UI:

use eseperio\virtualfields\models\VirtualFieldDefinition;

$field = new VirtualFieldDefinition([
    'entity_type' => 1, // User entity type
    'name' => 'phone_number',
    'label' => 'Phone Number',
    'data_type' => 'string',
    'required' => true,
    'active' => true,
]);
$field->save();

$field2 = new VirtualFieldDefinition([
    'entity_type' => 1,
    'name' => 'birth_date',
    'label' => 'Date of Birth',
    'data_type' => 'date',
    'required' => false,
    'active' => true,
]);
$field2->save();

Using Virtual Fields

Once defined, virtual fields work like native model properties:

$user = User::findOne(1);

// Get virtual field value
echo $user->phone_number;

// Set virtual field value
$user->phone_number = '+1234567890';
$user->birth_date = '1990-01-15';

// Save (automatically saves virtual fields)
$user->save();

// Mass assignment works too
$user->load(Yii::$app->request->post());
$user->save();

Virtual fields are automatically saved when you call save() on the model. The behavior hooks into Yii2's afterInsert and afterUpdate events to persist virtual field changes.

Note: A saveVirtualFields() method is also available if you need to manually trigger saving of virtual fields, though this is rarely necessary in typical usage.

Using in Forms

Virtual fields integrate seamlessly with ActiveForm:

use eseperio\virtualfields\helpers\VirtualFieldRenderer;

$form = ActiveForm::begin();

// Render standard fields
echo $form->field($model, 'username');
echo $form->field($model, 'email');

// Get virtual field definitions
$module = Yii::$app->getModule('virtualFields');
$service = $module->get('service');
$definitions = $service->getDefinitions($model->getObjectType());

// Render all virtual fields
echo VirtualFieldRenderer::renderFields($form, $model, $definitions);

// Or render individual fields
foreach ($definitions as $definition) {
    echo VirtualFieldRenderer::renderField($form, $model, $definition);
}

ActiveForm::end();

Using in DetailView

use yii\widgets\DetailView;
use eseperio\virtualfields\helpers\DetailViewHelper;

// Get virtual field definitions
$module = Yii::$app->getModule('virtualFields');
$service = $module->get('service');
$definitions = $service->getDefinitions($model->getObjectType());

// Build attributes array
$attributes = [
    'id',
    'username',
    'email',
];

// Add virtual field attributes
$attributes = array_merge($attributes, DetailViewHelper::getAttributes($definitions));

// Render DetailView
echo DetailView::widget([
    'model' => $model,
    'attributes' => $attributes,
]);

Using in GridView

use yii\grid\GridView;
use eseperio\virtualfields\helpers\GridViewHelper;

// Get virtual field definitions
$module = Yii::$app->getModule('virtualFields');
$service = $module->get('service');
$definitions = $service->getDefinitions(1); // User entity type

// Build columns array
$columns = [
    'id',
    'username',
    'email',
];

// Add virtual field columns
$columns = array_merge($columns, GridViewHelper::getColumns($definitions));

// Render GridView
echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => $columns,
]);

Supported Data Types

The extension supports the following data types out of the box:

Type Description PHP Type Example
string Short text string "John Doe"
text Long text string "Lorem ipsum..."
int Integer number integer 42
float Decimal number float 3.14
bool Boolean boolean true/false
date Date string "2024-01-15"
datetime Date and time string "2024-01-15 14:30:00"
json JSON data array {"key": "value"}

Custom Data Types

You can register custom data types:

$module = Yii::$app->getModule('virtualFields');
$service = $module->get('service');

$service->registerDataType(
    'custom_type',
    function($value) { /* cast */ return $value; },
    function($value) { /* serialize */ return (string)$value; },
    function($value) { /* deserialize */ return $value; }
);

Field Name Validation

The extension automatically validates field names to prevent collisions:

  • ✅ Checks against database columns
  • ✅ Checks against existing properties
  • ✅ Checks against getter/setter methods
  • ✅ Validates naming patterns (alphanumeric + underscore)
  • ✅ Prevents use of reserved names

Architecture

Entity Type Mapping

The extension uses integer IDs to identify entity types internally. This design:

  • Provides a stable, efficient identifier
  • Allows flexibility in class naming/refactoring
  • Enables multi-tenant scenarios

Configure the mapping in the module's entityMap property.

Database Schema

virtual_field_definition table stores:

  • Entity type (integer)
  • Field name
  • Data type
  • Validation rules (required, multiple values)
  • Options (JSON)
  • Active status

virtual_field_value table stores:

  • Definition reference
  • Entity type and ID
  • Value (stored as text, cast by type)

Caching

Field definitions are cached for performance. Cache is automatically invalidated when definitions change.

Best Practices

  1. Choose appropriate entity type IDs: Use a systematic numbering scheme
  2. Be mindful of field names: Avoid names that might conflict with future model properties
  3. Use appropriate data types: This ensures proper validation and rendering
  4. Test thoroughly: Virtual fields should be tested like any other model attribute
  5. Consider performance: Virtual fields require additional database queries

Troubleshooting

Virtual fields not appearing

  • Ensure the behavior is attached to your model
  • Verify getObjectType() returns the correct entity type ID
  • Check that field definitions are active
  • Clear cache: Yii::$app->cache->flush()

Validation not working

  • Ensure validation rules are properly set in the field definition
  • Check that the behavior's beforeValidate event is being triggered

Name collision errors

  • Choose different field names that don't conflict with existing properties
  • Review the validation error message for specific conflicts

Testing

This library includes comprehensive functional tests using Codeception and SQLite.

Running Tests

  1. Install dependencies:
composer install
  1. Run migrations to set up the test database:
composer test-migrate
  1. Run functional tests:
composer test-functional

Migration Structure

The library has two sets of migrations:

  • migrations/ - Library migrations (virtual field tables)

    • m000000_000000_create_virtual_field_definition_table.php
    • m000000_000001_create_virtual_field_value_table.php
  • tests/_app/migrations/ - Test app migrations (test models)

    • m000000_000002_create_test_model_table.php
    • m000000_000003_create_product_table.php

The composer test-migrate script runs both sets of migrations in the correct order.

License

MIT

Contributing

Contributions are welcome! Please submit pull requests or open issues on GitHub.

Credits

Developed by Eseperio.

eseperio/yii2-model-virtual-fields 适用场景与选型建议

eseperio/yii2-model-virtual-fields 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 27 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 11 月 28 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「extension」 「activerecord」 「yii2」 「dynamic fields」 「virtual fields」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 eseperio/yii2-model-virtual-fields 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 eseperio/yii2-model-virtual-fields 我们能提供哪些服务?
定制开发 / 二次开发

基于 eseperio/yii2-model-virtual-fields 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 27
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 31
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-11-28