ivankff/yii2-value-objects

Easy to store nested objects and typed collections in AR

Installs: 29

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 3

Forks: 0

Open Issues: 0

Type:yii2-extension

0.1.3 2020-09-21 14:44 UTC

This package is auto-updated.

Last update: 2024-04-21 22:28:50 UTC


README

Extend your ActiveRecord by nested objects and typed collections, serialized and stored in table field

Example

class User extends ActiveRecord
{
    // using value objects require attached behavior
    public function behaviors()
    {
        return [
            'valueObjects' => 'ivankff\valueObjects\ValueObjectsBehavior',
        ];
    }

    /**
     * Value objects map
     *
     * @param static $owner
     * @return array
     */
    public static function valueObjects($owner) {
        // define value objects on model attributes
        return [
            // $this->profile attribute will be an instance of defined anonymous class
            'profile' => new class extends ValueObject {
                public $github;
                public $phones = [];
            },
        ];
    }
}

$user = new User();
$user->profile->github = 'https://github.com/equicolor/';
$user->profile->phones[] = '555-55-555';
$user->save();

Now profile field of user table contains json:

{"github":"https://github.com/equicolor/","phones":["555-55-555"]}

It will be converted to object on afterFind event.

A more complex example with collections

<?php
use ivankff\valueObjects\ValueObject;
use yii\db\ActiveRecord; 

/**
 * @property integer $id
 * @property Offer $offer
 */
class Campaign extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'valueObjects' => 'ivankff\valueObjects\ValueObjectsBehavior',
        ];
    }
    /**
     * Value objects map
     *
     * @param static $owner
     * @return array
     */
    public static function valueObjects($owner) {
        return [
            // you can define value object as simple class
            'offer' => new Offer(['arAttribute' => 'offer_column_in_database']),
        ];
    }

    // other methods ...
}

Roadmap

  • Refactoring
  • Tests
  • Proper error handling
  • Validation
  • Separate serealization engine

You are welcome to create issues =)