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
Requires
- php: >=5.6
- yiisoft/yii2: ~2.0.14
This package is auto-updated.
Last update: 2025-02-22 00:07:11 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 =)