承接 spinitron/yii2-dynamic-ar 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

spinitron/yii2-dynamic-ar

Composer 安装命令:

composer require spinitron/yii2-dynamic-ar

包简介

Extends Yii ActiveRecord for Maria Dynamic Columns

README 文档

README

The yii2-dynamic-ar extension adds NoSQL-like documents to Yii 2 Framework's Active Record ORM.

Maria Dynamic Columns and PostgreSQL jsonb

Dynamic Columns in Maria 10.0+ and jsonb column types and functions in in PostgreSQL 9.4+ provide, in effect, a NoSQL document attached to every row of an SQL table. It's a powerful feature that allows you to do things that have been hard in relational DBs. Problems that might drive you to Couch or Mongo, or to commit a crime like EAV to your schema, can suddenly be easy when

  • records can have any number of attributes,
  • attribute names can be made up on the fly,
  • the dynamic attribute names don't appear in the schema,
  • dynamic attributes can be structured like an associative array.

Dynamic AR works for Maria now and will come to PostgreSQL in the future.

Example

An online shopping site has a table that stores info about each product.

CREATE TABLE product (
    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    sku VARCHAR(32),
    upc VARCHAR(32),
    title VARCHAR(255),
    price DECIMAL(9, 2),
    stock INT(11),
    details LONGBLOB NOT NULL
);

In this (simplistic) example, details will hold the Maria Dynamic Column blob and is declared in the model class by the dynamicColumn() method. Everything else in a Dynamic AR class declaration is familiar AR stuff.

class Product extends \spinitron\dynamicAr\DynamicActiveRecord
{
    public static function tableName()
    {
        return 'product';
    }

    public static function dynamicColumn()
    {
        return 'details';
    }
}

Now we can do all the normal AR things with Product but in addition we can read, write and update attributes not mentioned in the schema.

$product = new Product([
    'sku' => 5463,
    'upc' => '234569',
    'price' => 4.99,
    'title' => 'Clue-by-four',
    'description' => 'Used for larting lusers or constructing things',
    'dimensions' => [
        'unit' => 'inch',
        'width' => 4,
        'height' => 2,
        'length' => 20,
    ],
    'material' => 'wood',
]);
$product->save();

Think of the details table column as holding a serialized associative array. But unlike saving a JSON document in a text field, you can use dynamic attributes anywhere in your code, including in queries, just as you do with schema attributes. The differences are

  • Nested attributes use dotted notation, e.g. dimensions.length
  • Direct get and set of nested attributes on a model instance use the getAttribute() and setAttribute() methods because PHP doesn't allow dotted notation in identifiers.
  • When a dynamic attribute appears in a query, wrap it in bang-parens (! … !), e.g. (! dimensions.length !). (Space between attribute name and its bang-parens is optional so (!material!) is fine.)

For example

$model = new Product([
    'title' => 'Car',
    'specs.fuel.tank.capacity' => 50,
    'specs.fuel.tank.capacity.unit' => 'liter',
]);
$model->setAttribute('specs.wheels.count', 4);
$model = Product::find()->where(['(!dimensions.length!)' => 10]);
$section = Product::find()
    ->select('CONCAT((! dimensions.width !), " x ", (! dimensions.height !))')
    ->where(['id' => 11])
    ->one();

The dot notation works anywhere Yii accepts an attribute name string, for example

class Product extends \spinitron\dynamicAr\DynamicActiveRecord
{
    public function rules()
    {
        return [['dimensions.length', 'double', 'min' => 0.0]];
    }

    public function search($params)
    {
        $dataProvider = new \yii\data\ActiveDataProvider([
            'sort' => [
                'attributes' => [
                    'dimensions.length' => [
                        'asc' => ['(! dimensions.length !)' => SORT_DESC],
                        'desc' => ['(! dimensions.length !)' => SORT_ASC],
                    ],
                ],
            ],
            // ...
        ]);
    }
}

Design principle

DynamicActiveRecord adds a fourth to the three things that reading and writing AR model properties can do:

  1. $model->foo accesses, if it exists, the instance variable $foo,
  2. otherwise it accesses the column attribute foo, if the model's table has a column "foo",
  3. otherwise it accesses the virtual attribute foo, if the model's class has magic getFoo() / setFoo() methods,
  4. else $model->foo accesses a dynamic attribute named "foo".

So any attribute name that doesn't refer to one of the normal 3 kinds of AR model property (instance variable, column attribute, virtual attribute) is automatically a dynamic property as soon as you use it. There is no way to declare a dynamic property and you can only define one by writing to it.

And reading an attribute that doesn't exist returns null.

PHP null, SQL NULL and Maria

Maria does not encode a dynamic column set to SQL NULL:

SELECT COLUMN_CREATE('a', 1, 'b', null) = COLUMN_CREATE('a', 1)
>> 1

Thus if a table record currently has a dynamic column 'b' and Maria executes an update setting it to NULL then Maria removes 'b' from the record. (This makes sense if NULL has its conventional database meaning of 'data value does not exist.') So DynamicActiveRecord cannot possibly distinguish a NULL value from a dynamic column that doesn't exist after reading back from the DB.

In order to be consistent, DynamicActiveRecord always returns null when you read a dynamic attribute that hasn't been set, in contrast to ActiveRecord which throws an exception. But it also makes sense if null means 'does not exist' and given the design principle (above).

Further reading

Class reference

More documentation

Useful links

Regenerate docs in gh-pages branch

vendor/bin/apidoc api . . --template="spinitron\dynamicAr\doc\template\ApiRenderer"

Questions, comments, issues

Use the issue tracker. Or you can easily find my email if you prefer.

Copyright (c) 2015 Spinitron LLC

spinitron/yii2-dynamic-ar 适用场景与选型建议

spinitron/yii2-dynamic-ar 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 7.01k 次下载、GitHub Stars 达 57, 最近一次更新时间为 2015 年 08 月 11 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 spinitron/yii2-dynamic-ar 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 7.01k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 57
  • 点击次数: 10
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 57
  • Watchers: 16
  • Forks: 14
  • 开发语言: PHP

其他信息

  • 授权协议: ISC
  • 更新时间: 2015-08-11